Files
reverse-engineering-anything/tests/boundary/filesystem/setupClientConfigCleanupOwnership.test.ts
T
morluto cef87c498a refactor(architecture): add the ports and resources layers, move ports and shared resource owners there, and ratchet the layer baseline (#11208)
* test(architecture): fail on a stale layer baseline and document the declared layers

verify:module-boundaries reported a layer baseline entry whose imports were
gone but still passed, so main kept process -> artifacts at 20 after it fell
to 17 and a later change could add three imports back unnoticed. A stale
entry now fails like growth; --shrink-layer-baseline lowers it in the change
that removes the imports. The architecture map and CONTRIBUTING name
scripts/lib/module-layers.mjs as the per-directory layer declaration.

* test(architecture): refuse to lower the layer baseline after an inspection failure

A file that cannot be parsed contributes no imports, so a shrink run would record counts that fail as growth once the file is fixed. Whole-command tests cover stale rejection, shrinking, refused growth and the inspection failure.

* refactor(ports): move the progress, work-scope and inspection-scope ports to src/ports (#11214)

* refactor(ports): move the progress, work-scope and inspection-scope ports to src/ports

Pure move with git mv and import specifier updates.

* test(architecture): declare the ports layer and lower the layer baseline

src/ports sits between the foundation and the providers. Moving the three
ports removes 11 provider -> application imports.

* refactor(ports): move AnalysisProvider to src/ports (#11217)

* refactor(ports): move AnalysisProvider to src/ports

Pure move with git mv and import specifier updates in its importers, the
built-fixture path, the CI scope glob and the lint-rule test spellings.

* test(architecture): lower the layer baseline after moving AnalysisProvider

* refactor(ports): move the per-feature provider ports to src/ports (#11226)

* refactor(ports): move the per-feature provider ports to src/ports

Pure move with git mv and import specifier updates: the 47 *Port.ts and
*Ports.ts files that providers implement, plus OptionalObservationProviders,
which only composes the observation ports.

* test(architecture): lower the layer baseline after moving the feature ports

* refactor(providers): move closeAnalysisClient and the Frida session input errors to their owners (#11233)

* refactor(providers): move closeAnalysisClient to src/providers and the Frida session input errors to src/frida

Pure move with git mv and import specifier updates.

* test(architecture): drop the application-providers and application-frida cycles from the layer baseline

* fix(ci): keep provider lanes selecting the ports moved to src/ports

Each lane glob that matched a moved port under src/application gains its src/ports counterpart; the change-scope test pins one moved port per lane.

* refactor(domain): declare the localPath host exception and read HOST_PLATFORM there (#11256)

absoluteLocalPathStringSchema decides which paths are absolute on the running host, so it reads HOST_PLATFORM instead of process.platform. Domain may not import outside domain/contracts; module-layers now declares LAYER_EXCEPTIONS, exact file-to-file imports with a reason, and both the layer count and the pure-layer boundary skip only that import. Any other domain -> platform import still fails.

* refactor(ports): move the doctor check and provider inspection types to src/ports (#11246)

* refactor(ports): move the doctor check and provider inspection types to src/ports

Declaration move from application/Doctor.ts (unchanged text) and import updates; no re-export from Doctor.ts.

* test(architecture): lower the layer baseline after moving the doctor provider types

* refactor(ports): move the packet capture and signal recording ports to src/ports (#11249)

* refactor(ports): move the packet capture and signal recording ports to src/ports

Declaration move (unchanged text) out of the two application services, with import updates.

* test(architecture): lower the layer baseline after moving the capture and signal ports

* refactor(domain): move the analysis error projection schema from contracts to domain (#11251)

* refactor(domain): move the analysis error projection schema from contracts to domain

Declaration move (unchanged text) of the projection schemas that domain modules embed; contracts/errorSchemas.ts keeps the CLI envelope and the published JSON Schema. Import updates only.

* test(architecture): drop the contracts-domain cycle from the layer baseline

* refactor(ports): drop the imports the moved capture, signal and doctor types left behind

Also give the packet capture and signal recording lanes the new port paths, with change-scope cases.

* refactor(resources): add src/resources and move AnalysisCleanupLease and ArtifactReader there (#11259)

* refactor(resources): move AnalysisCleanupLease to src/resources

Pure move: git mv plus import specifier rewrites (source, tests, and the dist paths the verifier scripts load).

* refactor(resources): declare src/resources as a foundation unit

src/resources owns the shared analysis resource modules that process, windows and providers hold; AnalysisCleanupLease is the first. Its tests join the adapters project, the apk signature lane selects it beside src/artifacts, and the layer baseline drops the process and windows imports of the lease.

* test(ci): pin the apk signature lane on the moved cleanup lease

* refactor(resources): move ArtifactReader to src/resources

Pure move: git mv plus import specifier rewrites (source, tests, and the dist path a verifier script loads).

* test(architecture): lower the layer baseline after moving ArtifactReader

windows no longer imports src/artifacts; process -> artifacts 11 -> 9. The CI lanes that selected src/artifacts/ArtifactReader.ts select its new path, pinned in the change-scope test.

* refactor(resources): move ArtifactResourceScope to src/resources (#11265)

* refactor(artifacts): name the output tree and private root capabilities the resource scope releases

ArtifactResourceScope typed its output-tree and private-runtime-root owners with SafeOutputTree (src/artifacts) and PrivateRuntimeRoot (src/process). It only calls rollback() and close(), so it now declares those capabilities itself and names neither unit, which lets it move to src/resources without a resources <-> process cycle. The withheld-export test narrows to SafeOutputTree where it reads the published flag.

* refactor(resources): move ArtifactResourceScope to src/resources

Pure move: git mv plus import specifier rewrites (source, tests, the dist paths verifier scripts load, and the FIFO probe's module-relative URL).

* test(architecture): lower the layer baseline after moving ArtifactResourceScope

process -> artifacts 9 -> 5, and the artifacts <-> dotnet mutual pair is gone. The sqlite and agentenv lanes select the scope at its new path, pinned in the change-scope test.

* refactor(resources): move ArtifactFileOperation to src/resources (#11269)

* refactor(resources): move ArtifactFileOperation to src/resources

Pure move: git mv plus import specifier rewrites (source, tests, and the dist paths verifier scripts load).

* test(architecture): lower the layer baseline after moving ArtifactFileOperation

process -> artifacts 5 -> 1.

* refactor(resources): move readStableArtifact to src/resources (#11271)

* refactor(resources): move readStableArtifact to src/resources

Pure move: git mv plus import specifier rewrites.

* test(architecture): lower the layer baseline after moving readStableArtifact

process no longer imports src/artifacts: process -> artifacts 1 -> 0 and the artifacts <-> process mutual pair is gone. The seven lanes that selected readStableArtifact select its new path, pinned in the change-scope test; the architecture map lists what src/resources owns.

* refactor(hopper): take Linux launcher verification from composition through a port (#11278)

The Hopper launcher imported inspectLinuxHopperLauncher and retryLinuxHopperPublisherCleanup from src/application (the two hopper -> application imports). src/ports/LinuxHopperLauncherVerification.ts now names that capability; src/application/LinuxHopper.ts provides LINUX_HOPPER_LAUNCHER_VERIFICATION, binary composition passes it to HopperProvider, and the provider hands it to the launcher. A launcher built without one refuses a Linux demo launch with reason verification_unavailable before running the launcher. Layer baseline: hopper -> application 2 -> 0.

* refactor(config): move Hopper launcher discovery to a src/hopperPaths foundation unit (#11292)

* refactor(hopper): move the launcher discovery and macOS Hopper paths to src/hopperPaths

Pure move: git mv plus import specifier rewrites.

* refactor(hopper): declare src/hopperPaths as a foundation unit with the Linux launcher candidates

Hopper install paths and launcher discovery are pure path facts that the
Hopper provider, doctor and setup all read. Declare src/hopperPaths in the
foundation layer, add it to the adapters test project, the architecture
map and the package-baseline CI lane, and move the Linux launcher
candidates out of src/application/LinuxHopper.ts into
src/hopperPaths/LinuxHopperPaths.ts so discovery no longer imports
application code.

* refactor(config): leave Hopper launcher discovery to the Hopper provider

parseConfig resolved an unset HOPPER_LAUNCHER_PATH by probing the
filesystem through application-owned discovery, so config imported
application (config -> application 2, application <-> config cycle) and
read process.platform ambiently.

AppConfig.hopperLauncherPath is now the caller's HOPPER_LAUNCHER_PATH
unchanged (string | undefined). src/hopperPaths/HopperLauncherDiscovery.ts
owns the selection (selectedHopperLauncherPath: the configured spelling,
else discovery from the caller environment's home on the provider's
platform); HopperProvider and the two real-Hopper verifiers read it.
Discovery tests move from config.test.ts to src/hopperPaths; a provider
test covers discovery from the provider's own platform and home.

Module layers: config -> application 2 -> 0; application <-> config removed.
Architecture guards: ambient platform reads in parseConfig.ts 2 -> 0.

* refactor(providers): move owned-process prerequisite availability out of application (#11294)

* refactor(providers): move the owned-process prerequisite availability mapping to src/providers

Pure move: git mv plus import specifier rewrites.

* test(architecture): lower the layer baseline after moving owned-process availability

android -> application 1 -> 0; apktool -> application 1 -> 0.

* refactor(process): move the regular-file read owner out of application (#11299)

* refactor(process): move the regular-file read owner from src/application to src/process

Pure move: git mv plus import specifier rewrites.

* test(architecture): lower the layer baseline after moving the regular-file read owner

desktop -> application 5 -> 4; dotnet -> application 2 -> 1.

The agentenv lane listed src/application/RegularFileRead.ts. At its new
path it is a src/process/ shared boundary: fast qualification selects the
code and runtime checks (and the single owning lane, web_source_map, via
src/process/**), and full qualification selects every lane, as for every
other src/process/ module. A second owner entry would only suppress the
web_source_map selection, so the agentenv entry is removed, not renamed.

* refactor(resources): give atomic text writes their own owner (#11302)

* refactor(resources): give atomic text writes their own owner in src/resources

src/application/JsonFiles.ts owned both JSON input reads and the atomic
text write (writeTextFile / writeTextParts and their staged-output
publication). The write side depends only on domain, filesystem and
resource owners, but il2cpp's Ghidra seed writer had to import
application to reach it (il2cpp -> application).

Move the write side verbatim to src/resources/TextFileWrite.ts
(TextWriteCancellation, writeTextFile, writeTextParts and their private
staging, publication and failure classification helpers). JsonFiles keeps
the JSON read owner and reads the shared errno-to-reason classifier
(fileAccessFailureReason) from the write owner instead of a copy.
Importers (il2cpp seed writer, evidence bundle files, desktop build
solves, analysis snapshot files and four boundary tests) read the new
path; no re-export is left in JsonFiles.

* test(architecture): lower the layer baseline after moving the text write owner

il2cpp -> application 1 -> 0.

* refactor(ports): move the desktop build host contract to src/ports (#11303)

* refactor(domain): move the setup cancellation check from src/application to src/domain

Pure move: git mv plus import specifier rewrites.

* refactor(ports): move the desktop build host contract to src/ports

The desktop provider implements doctor's desktop build facts reader and
setup's desktop build host, but the contract it implements lived in
application (DesktopBuildDoctor, SetupDesktopBuild, Doctor's
clientRegistrations signature, ClientRegistrationEnvironment's setting
types), so desktop imported application four times and the two units
were a recorded mutual pair.

src/ports/DesktopBuildHost.ts now holds that contract, moved verbatim:
DesktopBuildCommand, DesktopBuildFacts, DesktopBuildFactsInput,
DesktopBuildSetupFacts, DesktopBuildSetupHost, RecordedProviderSettings
and OwnedProviderSetting. Two names are new: DesktopBuildRegistration,
the registration facts the host reads (client, command and the
recorded-settings names; client registration status satisfies it), and
DesktopBuildRegistrationReader, which replaces
DoctorHost["clientRegistrations"] in the setup host. The facts input's
registration reader returns DesktopBuildRegistration instead of the full
application status; the setup facts' settings are spelled
Readonly<Record<string, string>> (SetupProviderEnvironment's definition).
Application imports the types from the port; no re-export is left.

* test(architecture): lower the layer baseline after the desktop build host port

desktop -> application 4 -> 0; the application <-> desktop mutual pair is gone.

* refactor(domain): define the resolved app bundle resource root beside its schema (#11304)

* refactor(domain): define the resolved app bundle resource root beside its provenance schema

ResolvedAppBundleResourceRoot (an app directory's resource-only identity)
is a pure type over BundleResourceRoot's layout, but it lived in
src/application/AppBundleExecutable.ts, so the native and artifact
providers that receive it imported application.

Move the interface verbatim to src/domain/apple/bundleResourceRoot.ts,
which owns BundleResourceRoot, and point its eight readers there (native
macOS provider and plist source, artifact provider, binary composition,
and the binary session, status, port and bundle-resource session). The
resolver that produces it stays in application.

* test(architecture): lower the layer baseline after moving the resource root type

native -> application 2 -> 0; artifacts -> application 2 -> 1 (the
artifact provider still constructs BundleResourceSession).

* refactor(config): move the pwntools input bound parser to src/config (#11306)

* refactor(config): move the pwntools input bound parser from src/native to src/config

Pure move: git mv plus import specifier rewrites, and the module path in docs/design/rea-limit-inventory.md (table realigned by oxfmt).

* test(architecture): lower the layer baseline after moving the pwntools input bound

config -> native 1 -> 0. The binary_layout and recorded_crash lanes, which
select src/native/pwntools/**, also select src/config/pwntoolsInputLimit*.ts;
ciChangeScope.test.ts pins both.

* refactor(filesystem): move REA cache directory helpers out of config (#11309)

* refactor(filesystem): move the REA cache directory and lexical directory helpers from src/config to src/filesystem

Pure move: git mv plus import specifier rewrites.

* test(architecture): drop the config and filesystem cycle from the layer baseline

config no longer imports filesystem; filesystem still reads the Windows
ChangeTime settle budget from config.

* refactor(windows): break the process and windows import cycle (#11317)

* refactor(domain): move the runtime-control and private-runtime-root refusals from src/process to src/domain

Pure move: git mv plus import specifier rewrites (including the dist path scripts/verify-windows-native.mjs loads).

* refactor(windows): type Job Object cleanup by what a Windows job reports

WindowsOwnedProcess.cleanup() returned process-ownership's
ProcessCleanupResult, so src/windows imported src/process for a type while
process imports windows to supervise Windows trees. A Job Object stop only
ever reports settled-and-signalled or a reason it did not settle; name that
subset WindowsJobCleanupResult in windows. It stays assignable to
ProcessCleanupResult, so the process supervisor reads it unchanged.

* test(architecture): drop the process and windows cycle from the layer baseline

* test(architecture): ratchet cross-provider imports and imports past a provider entry (#11386)

* test(architecture): ratchet cross-provider imports and imports past a provider entry

A provider folder may import the domain, contracts, foundation and ports layers, the shared provider core (src/providers) and its own files; an import of another provider folder is a recorded exception. Application, composition and the CLI/MCP adapters reach a provider only through src/<provider>/index.ts. verify:module-boundaries counts both kinds of import per unit pair in the layer baseline (crossProvider, providerEntry); like the upward counts they may only shrink, and a pair missing from the baseline fails.

* refactor(resources): move StableArtifactFailure and StableArtifactObservation into src/resources (#11387)

* refactor(resources): move StableArtifactFailure and StableArtifactObservation into src/resources

Providers project stable-read failures through StableArtifactFailure next to the other shared provider toolkit owners (ArtifactReader, ArtifactResourceScope, ArtifactFileOperation, AnalysisCleanupLease, readStableArtifact) that already live in src/resources. Under src/artifacts it made every provider that reads a stable artifact import the artifacts provider. Pure move: git mv plus import specifier and baseline updates; the layer baseline drops the provider-boundary counts the move removes.

* refactor(resources): reach the shared provider toolkit through src/resources/index.ts (#11390)

* refactor(resources): import the shared provider toolkit through src/resources/index.ts

Adds src/resources/index.ts, which exports the toolkit names that production code outside src/resources uses, and rewrites those importers (420 files) to import from it, merging each importer's toolkit imports into one declaration. Mechanical: import declarations only.

* test(architecture): reach src/resources only through its entry file

verify:module-boundaries now counts any production import of a src/resources file other than src/resources/index.ts, from any unit, with the imports past a provider entry. The count is renamed from providerEntry to entry ("import past the entry file"); it may only shrink, and src/resources starts at zero.

* test(architecture): cover provider boundary counts through the verifier command

* refactor(resources): move the safe output tree and artifact path owners into src/resources (#11398)

* refactor(resources): move the safe output tree and artifact path owners into src/resources

SafeOutputTree (with its admission, creation failure, readback, cleanup and identity files), StreamBytes, ArtifactPaths and readArtifactFileChunks depend only on domain, filesystem, platform and the toolkit, and browser, firmware, ghidra, javascript, android and apktool use them to publish outputs. Under src/artifacts every such provider imported the artifacts provider. Pure move: git mv, importers moved onto src/resources/index.ts (names added to the entry), the moved files import toolkit modules directly, path keys in the CI scopes and guard baseline follow the move, and the layer baseline drops the removed imports.

* test(architecture): give the shared provider core its own layer below the providers (#11401)

src/providers (deferred client owners and failure attribution) now imports only domain, ports, process, filesystem and the resources toolkit. Declaring it as the providerCore layer, between ports and providers, makes any import from it into a provider folder an upward import that verify:module-boundaries rejects, and lets every unit in the providers layer be a provider folder.

* test(architecture): declare each provider's entry files instead of a provider barrel (#11407)

* chore: ignore the source map parser move (#11348) in blame

* test(architecture): declare inspector's use of the browser CDP client as a provider dependency (#11420)
2026-11-16 03:56:10 +08:00

1118 lines
39 KiB
TypeScript

import { HOST_PLATFORM } from "../../../src/platform/HostPlatform.js";
import { currentClientRegistrationCommand } from "../../../src/application/ClientRegistrationIdentity.js";
import {
lstat as fsLstat,
mkdir,
open as fsOpen,
readFile,
realpath as fsRealpath,
rename,
writeFile,
type FileHandle,
} from "node:fs/promises";
import { dirname, join } from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import {
readClientRegistrationInspections,
readClientRegistrationStatuses,
} from "../../../src/application/ClientRegistrationStatus.js";
import {
existingMaintenanceScope,
planIntegrationMaintenance,
} from "../../../src/application/UpdateMaintenance.js";
import { ArtifactResourceScope } from "../../../src/resources/ArtifactResourceScope.js";
import { ok } from "../../../src/domain/result.js";
import type { DoctorHost } from "../../../src/application/Doctor.js";
import { ConfigurationError } from "../../../src/domain/configurationErrors.js";
import {
filterClientsNeedingConfigure,
systemSetupHost,
} from "../../../src/application/SetupHost.js";
import { RegularFileCleanupFailure } from "../../../src/filesystem/OwnedRegularFile.js";
import { configureDetectedClients } from "../../../src/application/SetupClients.js";
import { configureClientConfiguration } from "../../../src/application/SetupClientConfiguration.js";
import {
systemUninstallHost,
runUninstall,
} from "../../../src/application/Uninstall.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { awaitAcknowledgement } from "../../fixtures/lifecycleAcknowledgement.js";
import { withVerifierCleanup } from "../../../scripts/lib/verifier-cleanup.mjs";
import { supportedClientRegistrationProfile } from "../../../src/application/SupportedClients.js";
vi.mock("node:fs/promises", async (importOriginal) => {
const actual = await importOriginal<typeof import("node:fs/promises")>();
return {
...actual,
open: vi.fn(actual.open),
lstat: vi.fn(actual.lstat),
realpath: vi.fn(actual.realpath),
};
});
const openMock = vi.mocked(fsOpen);
const lstatMock = vi.mocked(fsLstat);
const realpathMock = vi.mocked(fsRealpath);
let actualFs: typeof import("node:fs/promises");
beforeEach(async () => {
actualFs =
await vi.importActual<typeof import("node:fs/promises")>(
"node:fs/promises",
);
openMock.mockImplementation((...args) => actualFs.open(...args));
lstatMock.mockImplementation((...args) => actualFs.lstat(...args));
realpathMock.mockImplementation((...args) => actualFs.realpath(...args));
});
afterEach(() => {
openMock.mockReset();
lstatMock.mockReset();
realpathMock.mockReset();
});
const holdReadHandle = (
path: string,
reason: string,
initiallyHeld = true,
maxFailures = Number.POSITIVE_INFINITY,
) => {
const closeAttempts: FileHandle[] = [];
let released = false;
let held = initiallyHeld;
let remainingFailures = maxFailures;
openMock.mockImplementation(async (...args) => {
const handle = await actualFs.open(...args);
if (String(args[0]) !== path) return handle;
const nativeClose = handle.close.bind(handle);
vi.spyOn(handle, "close").mockImplementation(async () => {
closeAttempts.push(handle);
if (held && !released && remainingFailures > 0) {
remainingFailures -= 1;
throw new Error(reason);
}
await nativeClose();
});
return handle;
});
return {
closeAttempts,
hold: () => {
held = true;
},
release: () => {
released = true;
},
};
};
/** Linux setup host with its VS Code client configuration directory prepared. */
const preparedVsCodeSetupHost = async (prefix: string) => {
const home = await createTestTempDirectory(prefix);
const host = systemSetupHost(
{ platform: "linux", homeDirectory: home } as DoctorHost,
{ HOME: home, XDG_CONFIG_HOME: join(home, "xdg") },
);
const client = (await host.supportedClients()).find(
({ name }) => name === "vscode",
);
if (client === undefined) throw new Error("VS Code setup client missing");
await mkdir(dirname(client.configPath), { recursive: true });
return { home, host, client };
};
/** Release the held read handle and verify host cleanup retries that same owner. */
const expectCloseReclaimsHandle = async (
host: { close?: () => Promise<unknown> },
closeAttempts: readonly object[],
release: () => void,
) => {
const attemptsBeforeClose = closeAttempts.length;
release();
expect(await host.close?.()).toBeUndefined();
expect(closeAttempts).toHaveLength(attemptsBeforeClose + 1);
expect(closeAttempts.at(-1)).toBe(closeAttempts[0]);
};
/** Give up on the assertion path: release the handle and let cleanup close it. */
const cleanupHeldHandle = async (
host: { close?: () => Promise<unknown> },
release: () => void,
) => {
release();
await host.close?.();
};
it("retains invalid UTF-8 diagnostics and the uninstall read owner when close fails", async () => {
const home = await createTestTempDirectory("rea-uninstall-utf8-close-");
const path = join(home, "client.json");
const original = Buffer.from([0xff]);
await writeFile(path, original);
const { closeAttempts, release } = holdReadHandle(
path,
"held uninstall handle",
);
const host = systemUninstallHost(home, undefined, { HOME: home }, "linux");
try {
expect(
await host.removeClient({
name: "cursor",
registrationProfile: supportedClientRegistrationProfile("cursor"),
format: "json",
configPath: path,
}),
).toMatchObject({
status: "failed",
detail: expect.stringContaining("not valid UTF-8"),
});
expect(Buffer.compare(await readFile(path), original)).toBe(0);
expect(closeAttempts).toHaveLength(3);
expect(closeAttempts.every((handle) => handle === closeAttempts[0])).toBe(
true,
);
await expectCloseReclaimsHandle(host, closeAttempts, release);
} finally {
await cleanupHeldHandle(host, release);
}
});
it("stops uninstall and retains the backup read owner when its close fails", async () => {
const home = await createTestTempDirectory("rea-uninstall-backup-close-");
const path = join(home, "client.json");
const client = {
name: "cursor",
registrationProfile: supportedClientRegistrationProfile("cursor"),
format: "json",
configPath: path,
} as const;
await writeFile(path, '{"keep":"before setup"}\n');
expect(
await configureClientConfiguration(client, {}, ["rea", "mcp"]),
).toMatchObject({ status: "configured" });
const configured = await readFile(path, "utf8");
const { closeAttempts, release } = holdReadHandle(
`${path}.rea.backup`,
"held backup handle",
);
const host = systemUninstallHost(home, undefined, { HOME: home }, "linux");
try {
expect(await host.removeClient(client)).toEqual({
name: "cursor",
status: "failed",
detail: expect.stringMatching(
/could not be backed up.*no change.*permissions.*uninstall/i,
),
});
expect(await readFile(path, "utf8")).toBe(configured);
expect(closeAttempts).toHaveLength(2);
await expectCloseReclaimsHandle(host, closeAttempts, release);
} finally {
await cleanupHeldHandle(host, release);
}
});
it("keeps shared-ownership proof when the ownership read completes but its close fails", async () => {
// FreeBuff without a profile marker leaves its shared storage applicability-
// unverified. The completed ownership read is the proof that later read
// failures are blocking; discarding it softens every failure to retained,
// so purge runs while the active shared registration remains.
const home = await createTestTempDirectory("rea-freebuff-ownership-close-");
const setupHost = systemSetupHost(
{ platform: "linux", homeDirectory: home } as DoctorHost,
{ HOME: home },
);
const client = (await setupHost.supportedClients()).find(
({ name }) => name === "freebuff",
);
if (client === undefined) throw new Error("freebuff client missing");
await mkdir(dirname(client.configPath), { recursive: true });
await writeFile(
client.configPath,
JSON.stringify({ mcpServers: { other: { command: "other" } } }),
);
expect(
await configureClientConfiguration(client, {}, ["rea", "mcp"]),
).toMatchObject({ status: "configured" });
const state = join(home, ".rea", "state.json");
await mkdir(dirname(state), { recursive: true });
await writeFile(state, "{}\n");
const { release } = holdReadHandle(
client.configPath,
"held ownership read handle",
);
const host = systemUninstallHost(home, undefined, { HOME: home }, "linux");
try {
const result = await runUninstall(true, host);
expect(result.status).toBe("failed");
expect(result.items).toContainEqual(
expect.objectContaining({ name: "freebuff", status: "failed" }),
);
expect(result.items).toContainEqual(
expect.objectContaining({
name: "uninstall",
status: "skipped",
detail: expect.stringContaining(
"No REA registration, skill, or data was removed",
),
}),
);
// Data must not be purged while the shared registration is still active.
await expect(readFile(state, "utf8")).resolves.toBe("{}\n");
} finally {
await cleanupHeldHandle(host, release);
}
});
it("keeps shared-ownership proof when removal refuses a shadowed duplicate", async () => {
// The effective row is REA-owned while an earlier duplicate is foreign, so
// removal refuses the edit. That refusal must not erase ownership: without
// the positive row fact, recurring close failures soften to retained and
// purge runs while the owned row remains active.
const home = await createTestTempDirectory("rea-freebuff-shadowed-close-");
const setupHost = systemSetupHost(
{ platform: "linux", homeDirectory: home } as DoctorHost,
{ HOME: home },
);
const client = (await setupHost.supportedClients()).find(
({ name }) => name === "freebuff",
);
if (client === undefined) throw new Error("freebuff client missing");
await mkdir(dirname(client.configPath), { recursive: true });
await writeFile(
client.configPath,
'{"mcpServers":{"rea":{"command":"foreign-server","args":[]},"rea":{"command":"rea","args":["mcp"]}}}',
);
const state = join(home, ".rea", "state.json");
await mkdir(dirname(state), { recursive: true });
await writeFile(state, "{}\n");
const { release } = holdReadHandle(
client.configPath,
"held ownership read handle",
);
const host = systemUninstallHost(home, undefined, { HOME: home }, "linux");
try {
const result = await runUninstall(true, host);
expect(result.status).toBe("failed");
expect(result.items).toContainEqual(
expect.objectContaining({ name: "freebuff", status: "failed" }),
);
expect(result.items).toContainEqual(
expect.objectContaining({
name: "uninstall",
status: "skipped",
detail: expect.stringContaining(
"No REA registration, skill, or data was removed",
),
}),
);
await expect(readFile(state, "utf8")).resolves.toBe("{}\n");
} finally {
await cleanupHeldHandle(host, release);
}
});
it("stops removal when a completed reread leaves its handle unreleased", async () => {
// Greptile P1: preflight and reread both complete with a foreign-only row,
// but the reread handle cannot be closed even by the cleanup retry. REA
// still owns that open handle, so removal must stop before purge: serving
// the completed text would let removeAll delete managed data while the
// incomplete cleanup is only reported later, by close().
const home = await createTestTempDirectory("rea-freebuff-reread-leak-");
const setupHost = systemSetupHost(
{ platform: "linux", homeDirectory: home } as DoctorHost,
{ HOME: home },
);
const client = (await setupHost.supportedClients()).find(
({ name }) => name === "freebuff",
);
if (client === undefined) throw new Error("freebuff client missing");
await mkdir(dirname(client.configPath), { recursive: true });
await writeFile(
client.configPath,
'{"mcpServers":{"rea":{"command":"foreign-server","args":[]}}}',
);
const state = join(home, ".rea", "state.json");
await mkdir(dirname(state), { recursive: true });
await writeFile(state, "{}\n");
const { hold, release } = holdReadHandle(
client.configPath,
"held removal reread handle",
false,
);
const base = systemUninstallHost(home, undefined, { HOME: home }, "linux");
const host = {
...base,
inspectSkill: async () => {
hold();
return base.inspectSkill?.();
},
};
try {
const result = await runUninstall(true, host);
expect(result.status).toBe("failed");
expect(result.items).toContainEqual(
expect.objectContaining({
name: "freebuff",
status: "failed",
detail: expect.stringContaining("its resources could not be released"),
}),
);
expect(result.items).toContainEqual(
expect.objectContaining({
name: "uninstall",
status: "skipped",
detail: expect.stringContaining("Uninstall stopped at this failure"),
}),
);
// Managed data must survive an unreleased read handle.
await expect(readFile(state, "utf8")).resolves.toBe("{}\n");
} finally {
await cleanupHeldHandle(host, release);
}
});
it("keeps the shared registration fail-closed when ZCode's probe is unresolved", async () => {
// A denied profile probe leaves ZCode's applicability unresolved, never
// absent: the shared file stays fail-closed so its row is inspected and
// removed instead of leaving an installed ZCode wired to purged data.
// Definitive absence still leaves the file to FreeBuff, ZCode's owner.
const home = await createTestTempDirectory("rea-zcode-fallback-unresolved-");
const fallback = join(home, ".agents", "mcp.json");
const profile = join(home, ".zcode", "cli");
lstatMock.mockImplementation((path) =>
String(path) === profile
? Promise.reject(
Object.assign(new Error("EACCES: permission denied, lstat"), {
code: "EACCES",
}),
)
: actualFs.lstat(path),
);
const unresolved = systemUninstallHost(
home,
undefined,
{ HOME: home },
"linux",
);
try {
const rows = (await unresolved.clients()).filter(
(candidate) => candidate.configPath === fallback,
);
// One physical file, one owner: FreeBuff edits the shared file once and
// ZCode reports that same outcome instead of racing it to "absent".
expect(rows).toHaveLength(1);
expect(rows[0]).toMatchObject({ name: "freebuff", sharedWith: ["zcode"] });
// Fail-closed: the unresolved reader carries no unverified softening, so a
// failed read blocks removal instead of retaining around the purge.
expect(rows[0]?.applicability).toBeUndefined();
} finally {
await unresolved.close?.();
}
lstatMock.mockImplementation((...args) => actualFs.lstat(...args));
const absent = systemUninstallHost(home, undefined, { HOME: home }, "linux");
try {
const rows = (await absent.clients()).filter(
(candidate) => candidate.configPath === fallback,
);
expect(rows).toHaveLength(1);
// Definitive absence keeps ZCode out of another product's primary storage.
expect(rows[0]?.sharedWith).toBeUndefined();
} finally {
await absent.close?.();
}
});
it("removes a shared registration once and reports that outcome to both clients", async () => {
// ZCode and FreeBuff both load ~/.agents/mcp.json. Queuing it per client
// removed the row as ZCode and then reported FreeBuff as "absent", losing
// the outcome for the client that owns the file, and it read and edited one
// shared resource twice.
const home = await createTestTempDirectory("rea-shared-removal-once-");
const shared = join(home, ".agents", "mcp.json");
await mkdir(join(home, ".zcode", "cli"), { recursive: true });
await mkdir(join(home, ".config", "freebuff-desktop"), { recursive: true });
expect(
await configureClientConfiguration(
{
name: "freebuff",
registrationProfile: supportedClientRegistrationProfile("freebuff"),
format: "json",
configPath: shared,
},
{},
["rea", "mcp"],
),
).toMatchObject({ status: "configured" });
const host = systemUninstallHost(home, undefined, { HOME: home }, "linux");
try {
const result = await runUninstall(false, host);
expect(result.status).toBe("complete");
expect(result.items).toContainEqual(
expect.objectContaining({
name: "freebuff",
status: "removed",
configuration_path: shared,
}),
);
// The fallback reader reports the owner's removal, never "absent".
const zcode = result.items.find(({ name }) => name === "zcode");
expect(zcode?.actions).toContainEqual(
expect.objectContaining({
status: "removed",
configuration_path: shared,
}),
);
expect(zcode?.actions).not.toContainEqual(
expect.objectContaining({
status: "skipped",
configuration_path: shared,
}),
);
expect(JSON.parse(await readFile(shared, "utf8"))).toEqual({
mcpServers: {},
});
} finally {
await host.close?.();
}
});
it("keeps one row per client when OpenCode is pointed at FreeBuff's file", async () => {
// OPENCODE_CONFIG can make OpenCode and FreeBuff edit one file with different
// tables (`mcp.rea` and `mcpServers.rea`). Sharing one decision by filename
// would remove only OpenCode's row and report it for FreeBuff too, leaving
// FreeBuff registered while uninstall reports complete.
const home = await createTestTempDirectory("rea-shared-dialects-");
const shared = join(home, ".agents", "mcp.json");
await mkdir(dirname(shared), { recursive: true });
await mkdir(join(home, ".config", "freebuff-desktop"), { recursive: true });
expect(
await configureClientConfiguration(
{
name: "freebuff",
registrationProfile: supportedClientRegistrationProfile("freebuff"),
format: "json",
configPath: shared,
},
{},
["rea", "mcp"],
),
).toMatchObject({ status: "configured" });
const host = systemUninstallHost(
home,
undefined,
{ HOME: home, OPENCODE_CONFIG: shared },
"linux",
);
try {
const rows = (await host.clients()).filter(
(candidate) => candidate.configPath === shared,
);
expect(rows.map(({ name }) => name).sort()).toEqual([
"freebuff",
"opencode",
]);
expect(await runUninstall(false, host)).toMatchObject({
status: "complete",
});
expect(JSON.parse(await readFile(shared, "utf8"))).toEqual({
mcpServers: {},
});
} finally {
await host.close?.();
}
});
it.each([true, false])(
"projects only the shared table's outcome to ZCode (shared row owned: %s)",
async (sharedOwned) => {
const home = await createTestTempDirectory("rea-shared-table-outcome-");
const shared = join(home, ".agents", "mcp.json");
const zcodePath = join(home, ".zcode", "cli", "config.json");
await mkdir(dirname(shared), { recursive: true });
await mkdir(dirname(zcodePath), { recursive: true });
await writeFile(zcodePath, '{"mcp":{"servers":{}}}');
await writeFile(
shared,
JSON.stringify({
mcp: {
rea: {
type: "local",
command: [sharedOwned ? "foreign-server" : "rea", "mcp"],
},
},
mcpServers: {
rea: {
command: sharedOwned ? "rea" : "foreign-server",
args: ["mcp"],
},
},
}),
);
const host = systemUninstallHost(
home,
undefined,
{ HOME: home, OPENCODE_CONFIG: shared },
"linux",
);
try {
const result = await runUninstall(false, host);
expect(result.status).toBe("complete");
const zcode = result.items.find(({ name }) => name === "zcode");
expect(zcode?.status).toBe(sharedOwned ? "removed" : "retained");
expect(
zcode?.actions?.filter(
({ configuration_path }) => configuration_path === shared,
),
).toEqual([
expect.objectContaining({
status: sharedOwned ? "removed" : "retained",
}),
]);
const remaining = JSON.parse(await readFile(shared, "utf8"));
expect(remaining.mcp).toEqual(
sharedOwned
? { rea: { type: "local", command: ["foreign-server", "mcp"] } }
: {},
);
expect(remaining.mcpServers).toEqual(
sharedOwned
? {}
: { rea: { command: "foreign-server", args: ["mcp"] } },
);
} finally {
await host.close?.();
}
},
);
it("does not treat a dangling FreeBuff profile link as installed", async () => {
// Setup and doctor follow ~/.config/freebuff-desktop and reject a link whose
// target is gone. Discovery must agree: counting the leftover link as an
// installed product turns an unrelated malformed shared file into a blocking
// failure that stops every other REA removal.
const home = await createTestTempDirectory("rea-freebuff-dangling-profile-");
const shared = join(home, ".agents", "mcp.json");
const profile = join(home, ".config", "freebuff-desktop");
const cursor = join(home, ".cursor", "mcp.json");
await mkdir(dirname(shared), { recursive: true });
await writeFile(shared, "{ not json");
await mkdir(dirname(cursor), { recursive: true });
await writeFile(cursor, '{"keep":"before setup"}\n');
expect(
await configureClientConfiguration(
{
name: "cursor",
registrationProfile: supportedClientRegistrationProfile("cursor"),
format: "json",
configPath: cursor,
},
{},
["rea", "mcp"],
),
).toMatchObject({ status: "configured" });
lstatMock.mockImplementation((path) =>
String(path) === profile
? Promise.resolve({
isFile: () => false,
isDirectory: () => false,
isSymbolicLink: () => true,
} as unknown as Awaited<ReturnType<typeof fsLstat>>)
: actualFs.lstat(path),
);
realpathMock.mockImplementation((path) =>
String(path) === profile
? Promise.reject(
Object.assign(
new Error("ENOENT: no such file or directory, realpath"),
{ code: "ENOENT" },
),
)
: actualFs.realpath(path),
);
const host = systemUninstallHost(home, undefined, { HOME: home }, "linux");
try {
const result = await runUninstall(false, host);
expect(result.status).toBe("complete");
// The unrelated registration is removed instead of blocked.
expect(result.items).toContainEqual(
expect.objectContaining({ name: "cursor", status: "removed" }),
);
expect(JSON.parse(await readFile(cursor, "utf8"))).not.toHaveProperty(
"mcpServers.rea",
);
expect(result.items).toContainEqual(
expect.objectContaining({ name: "freebuff", status: "retained" }),
);
} finally {
await host.close?.();
}
});
it("serves a completed removal reread when its close retry releases the handle", async () => {
// Preflight saw no owned row; another writer adds one before removal. The
// reread's first close fails but its cleanup retry releases the handle:
// the completed text is the ownership evidence that drives removal of the
// concurrently added row instead of softening to retained and leaving it
// active while data is purged.
const home = await createTestTempDirectory("rea-freebuff-reread-close-");
const setupHost = systemSetupHost(
{ platform: "linux", homeDirectory: home } as DoctorHost,
{ HOME: home },
);
const client = (await setupHost.supportedClients()).find(
({ name }) => name === "freebuff",
);
if (client === undefined) throw new Error("freebuff client missing");
await mkdir(dirname(client.configPath), { recursive: true });
await writeFile(
client.configPath,
'{"mcpServers":{"rea":{"command":"foreign-server","args":[]}}}',
);
const cacheOwned = join(home, ".rea", "cache", "owned");
await mkdir(dirname(cacheOwned), { recursive: true });
await writeFile(cacheOwned, "owned\n");
const { hold, release } = holdReadHandle(
client.configPath,
"held removal reread handle",
false,
1,
);
const base = systemUninstallHost(home, undefined, { HOME: home }, "linux");
const host = {
...base,
inspectSkill: async () => {
// Another writer registers REA between preflight and removal.
await writeFile(
client.configPath,
'{"mcpServers":{"rea":{"command":"rea","args":["mcp"]}}}',
);
hold();
return base.inspectSkill?.();
},
};
try {
const result = await runUninstall(true, host);
expect(result.status).toBe("complete");
expect(result.items).toContainEqual(
expect.objectContaining({ name: "freebuff", status: "removed" }),
);
expect(await readFile(client.configPath, "utf8")).not.toContain("rea");
await expect(readFile(cacheOwned)).rejects.toMatchObject({
code: "ENOENT",
});
} finally {
await cleanupHeldHandle(host, release);
}
});
describe("ZCode fallback cleanup ownership", () => {
it.each(["preflight", "configure"])(
"retains a failed ZCode fallback close during %s until host cleanup",
async (operation) => {
const home = await createTestTempDirectory("rea-zcode-fallback-close-");
const host = systemSetupHost(
{ platform: "linux", homeDirectory: home } as DoctorHost,
{ HOME: home },
);
const client = (await host.supportedClients()).find(
({ name }) => name === "zcode",
);
if (client?.zcodeFallbackPath === undefined)
throw new Error("ZCode fallback path missing");
const fallback = client.zcodeFallbackPath;
await mkdir(dirname(fallback), { recursive: true });
const original = '{"mcpServers":{"other":{"command":"other"}}}\n';
await writeFile(fallback, original);
const { closeAttempts, release } = holdReadHandle(
fallback,
"held fallback handle",
);
try {
const action =
operation === "preflight"
? host.inspectClientConfiguration?.(client, {}, ["rea", "mcp"])
: host.configureClient(client, {}, ["rea", "mcp"]);
if (action === undefined) throw new Error("setup preflight missing");
await expect(action).rejects.toMatchObject({
_tag: "ConfigurationError",
cause: expect.any(RegularFileCleanupFailure),
cleanup: { resources: [fallback] },
});
expect(closeAttempts).toHaveLength(2);
expect(closeAttempts[0]).toBe(closeAttempts[1]);
expect(await readFile(fallback, "utf8")).toBe(original);
await expect(readFile(client.configPath)).rejects.toMatchObject({
code: "ENOENT",
});
await expectCloseReclaimsHandle(host, closeAttempts, release);
} finally {
await cleanupHeldHandle(host, release);
}
},
);
});
describe("setup client configuration cleanup ownership", () => {
it.each([
["valid UTF-8", Buffer.from('{"servers": {"other": {}}}\n')],
["malformed UTF-8", Buffer.from([0xff])],
] as const)(
"stops configuration and retains the %s read owner until host close",
async (encoding, original) => {
const { host, client } = await preparedVsCodeSetupHost(
"rea-setup-config-close-",
);
await writeFile(client.configPath, original);
const { closeAttempts, release } = holdReadHandle(
client.configPath,
"test holds the config handle open",
);
const configure = vi.spyOn(host, "configureClient");
try {
const failure = await filterClientsNeedingConfigure(
host,
[client],
{ providerEnvironment: {} },
["rea", "mcp"],
)
.then((detectedClients) =>
configureDetectedClients({
host,
detectedClients,
providerEnvironment: {},
command: ["rea", "mcp"],
clients: {},
appliedActions: [],
}),
)
.then(
() => undefined,
(cause: unknown) => cause,
);
expect(failure).toBeInstanceOf(ConfigurationError);
if (!(failure instanceof ConfigurationError))
throw new Error(
"Expected the configuration failure to retain cleanup authority",
);
if (encoding === "malformed UTF-8")
expect(failure).toMatchObject({
cause: {
outcome: { kind: "failed", cause: expect.any(TypeError) },
},
});
expect(failure).toMatchObject({
_tag: "ConfigurationError",
cause: expect.any(RegularFileCleanupFailure),
cleanup: {
resources: [client.configPath],
reason: expect.stringContaining(
"test holds the config handle open",
),
},
});
expect(configure).not.toHaveBeenCalled();
expect(closeAttempts).toHaveLength(2);
expect(closeAttempts[0]).toBe(closeAttempts[1]);
expect(
Buffer.compare(await readFile(client.configPath), original),
).toBe(0);
await expectCloseReclaimsHandle(host, closeAttempts, release);
expect(failure.cleanupIncomplete).toBe(false);
expect(failure.cleanupResources).toEqual([]);
} finally {
await cleanupHeldHandle(host, release);
}
},
);
it("waits for an admitted configuration read and rejects later admissions", async () => {
const { host, client } = await preparedVsCodeSetupHost(
"rea-setup-config-inflight-",
);
await writeFile(client.configPath, '{"servers": {}}\n');
let beginRead!: () => void;
const readStarted = new Promise<void>((resolve) => {
beginRead = resolve;
});
let unblockRead!: () => void;
const readGate = new Promise<void>((resolve) => {
unblockRead = resolve;
});
let heldRead = false;
openMock.mockImplementation(async (...args) => {
const handle = await actualFs.open(...args);
if (String(args[0]) !== client.configPath || heldRead) return handle;
heldRead = true;
const nativeRead = handle.read.bind(handle);
vi.spyOn(handle, "read").mockImplementation(async (...readArgs) => {
beginRead();
await readGate;
return nativeRead(...readArgs);
});
return handle;
});
let hostCloseFinished = false;
const alignment = host.clientNeedsConfigure(client, {}, ["rea", "mcp"]);
let closeResult: ReturnType<NonNullable<typeof host.close>> | undefined;
await withVerifierCleanup(async () => {
await awaitAcknowledgement(readStarted, alignment, "configuration read");
const close = host.close;
if (close === undefined) throw new Error("Setup host close is missing");
closeResult = close().then((result) => {
hostCloseFinished = true;
return result;
});
const lateAdmission = await host
.clientNeedsConfigure(client, {}, ["rea", "mcp"])
.then(
() => undefined,
(cause: unknown) => cause,
);
expect(lateAdmission).toBeInstanceOf(ConfigurationError);
expect(lateAdmission).toMatchObject({
message: expect.stringContaining("Artifact resource scope is closed"),
});
expect(hostCloseFinished).toBe(false);
unblockRead();
await expect(alignment).resolves.toBe(true);
expect(await closeResult).toBeUndefined();
expect(hostCloseFinished).toBe(true);
}, [
unblockRead,
async () => {
await alignment;
},
async () => {
await closeResult;
},
async () => {
await host.close?.();
},
]);
});
});
const unscopedRegistrationReaders: readonly {
readonly name: string;
readonly read: (
home: string,
environment: NodeJS.ProcessEnv,
execute: Parameters<typeof planIntegrationMaintenance>[3],
) => Promise<unknown>;
}[] = [
{
name: "inspections",
read: (home, environment) =>
readClientRegistrationInspections(home, "/current/rea", {
platform: HOST_PLATFORM.platform,
environment,
}),
},
{
name: "statuses",
read: (home, environment) =>
readClientRegistrationStatuses(home, "/current/rea", {
platform: HOST_PLATFORM.platform,
environment,
}),
},
{
name: "maintenance scope",
read: (home, environment) =>
existingMaintenanceScope(home, "/current/rea", environment, {
platform: HOST_PLATFORM.platform,
}),
},
{
name: "maintenance plan",
read: (home, environment, execute) =>
planIntegrationMaintenance(home, "/current/rea", environment, execute, {
platform: HOST_PLATFORM.platform,
}),
},
];
it.each(
unscopedRegistrationReaders.flatMap((reader) =>
["configuration", "policy"].flatMap((source) =>
["completed", "failed"].map((readOutcome) => ({
...reader,
source,
readOutcome,
})),
),
),
)(
"$name transfers the exact $source owner after a $readOutcome read without a supplied scope",
async ({ read, source, readOutcome }) => {
const home = await createTestTempDirectory(
"rea-registration-unscoped-close-",
);
const config = join(
home,
source === "policy" ? ".gemini/settings.json" : ".cursor/mcp.json",
);
await mkdir(dirname(config), { recursive: true });
const registration =
'{"mcpServers":{"rea":{"command":"rea","args":["mcp"]}}}\n';
await writeFile(config, registration);
const heldPath = source === "policy" ? join(home, "system.json") : config;
const heldText = source === "policy" ? "{}\n" : registration;
await writeFile(
heldPath,
readOutcome === "failed" ? Buffer.from([0xff]) : heldText,
);
const environment = {
HOME: home,
GEMINI_CLI_SYSTEM_SETTINGS_PATH: join(home, "system.json"),
GEMINI_CLI_SYSTEM_DEFAULTS_PATH: join(home, "absent-defaults.json"),
};
const held = holdReadHandle(
heldPath,
"held standalone registration descriptor",
);
const execute = vi.fn(async () =>
ok('{"status":"planned","plannedActions":[]}'),
);
try {
const outcome = await read(home, environment, execute).then(
(value) => ({ kind: "returned" as const, value }),
(cause: unknown) => ({ kind: "threw" as const, cause }),
);
expect(outcome).toMatchObject({
kind: "threw",
cause: expect.any(RegularFileCleanupFailure),
});
if (
outcome.kind !== "threw" ||
!(outcome.cause instanceof RegularFileCleanupFailure)
)
throw new Error("Read lost its failed cleanup owner");
const failure = outcome.cause;
expect(failure.path).toBe(heldPath);
if (readOutcome === "completed")
expect(failure.outcome).toEqual({ kind: "completed", value: heldText });
else
expect(failure.outcome).toMatchObject({
kind: "failed",
cause: { _tag: "InvalidUtf8FileError", path: heldPath },
});
expect(failure.owner.handle).toBe(held.closeAttempts[0]);
await expect(failure.owner.close()).rejects.toThrow("held standalone");
await rename(heldPath, `${heldPath}.retired`);
await writeFile(heldPath, "replacement");
held.release();
await failure.owner.close();
expect(failure.owner.handle.fd).toBe(-1);
expect(new Set(held.closeAttempts).size).toBe(1);
expect(await readFile(heldPath, "utf8")).toBe("replacement");
expect(execute).not.toHaveBeenCalled();
} finally {
held.release();
for (const handle of new Set(held.closeAttempts)) await handle.close();
}
},
);
it("keeps a supplied registration scope responsible for diagnostics and cleanup retry", async () => {
const home = await createTestTempDirectory("rea-registration-scoped-close-");
const config = join(home, ".cursor/mcp.json");
await mkdir(dirname(config), { recursive: true });
await writeFile(
config,
'{"mcpServers":{"rea":{"command":"rea","args":["mcp"]}}}',
);
const held = holdReadHandle(config, "held scoped registration descriptor");
const resources = new ArtifactResourceScope();
try {
expect(
(
await readClientRegistrationStatuses(home, "/current/rea", {
platform: HOST_PLATFORM.platform,
environment: { HOME: home },
resources,
})
).find((status) => status.client === "cursor"),
).toMatchObject({ state: "invalid", command: [] });
expect(resources.hasPending).toBe(true);
await expect(resources.close()).rejects.toThrow();
held.release();
await resources.close();
expect(resources.hasPending).toBe(false);
expect(new Set(held.closeAttempts).size).toBe(1);
expect(held.closeAttempts[0]!.fd).toBe(-1);
} finally {
held.release();
await resources.close();
}
});
it("keeps a supplied maintenance scope responsible for a refresh-check read whose close fails", async () => {
const home = await createTestTempDirectory("rea-maintenance-refusal-close-");
const config = join(home, ".cursor/mcp.json");
await mkdir(dirname(config), { recursive: true });
const environment = { HOME: home };
const [command, ...args] = currentClientRegistrationCommand({
entrypointPath: "/current/rea",
environment,
});
await writeFile(
config,
JSON.stringify({ mcpServers: { rea: { command, args } } }),
);
// The registration inspection reads the file first; fail only the close of
// the refresh check's later read of the same file.
const closeAttempts: FileHandle[] = [];
let opens = 0;
let released = false;
openMock.mockImplementation(async (...openArgs) => {
const handle = await actualFs.open(...openArgs);
if (String(openArgs[0]) !== config) return handle;
opens += 1;
if (opens === 1) return handle;
const nativeClose = handle.close.bind(handle);
vi.spyOn(handle, "close").mockImplementation(async () => {
closeAttempts.push(handle);
if (!released) throw new Error("held refresh-check descriptor");
await nativeClose();
});
return handle;
});
const resources = new ArtifactResourceScope();
const execute = vi.fn(async () =>
ok('{"status":"planned","plannedActions":[]}'),
);
try {
const maintenance = await planIntegrationMaintenance(
home,
"/current/rea",
environment,
execute,
{ platform: HOST_PLATFORM.platform, resources },
);
expect(maintenance.status).toBe("unavailable");
expect(closeAttempts.length).toBeGreaterThan(0);
// The scope owns the failed close, so its close retries it.
expect(resources.hasPending).toBe(true);
await expect(resources.close()).rejects.toThrow();
released = true;
await resources.close();
expect(resources.hasPending).toBe(false);
expect(closeAttempts.every((handle) => handle.fd === -1)).toBe(true);
expect(execute).not.toHaveBeenCalled();
} finally {
released = true;
await resources.close();
}
});