fix(setup): preserve current recovery snapshots and decoding failures
This commit is contained in:
@@ -6,6 +6,17 @@ import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
|
||||
const cases = [
|
||||
{
|
||||
client: "cursor",
|
||||
path: ".cursor/mcp.json",
|
||||
text: "malformed UTF-8",
|
||||
bytes: Buffer.concat([
|
||||
Buffer.from('{"label":"'),
|
||||
Buffer.from([0xff]),
|
||||
Buffer.from('"}'),
|
||||
]),
|
||||
diagnostic: "not valid UTF-8",
|
||||
},
|
||||
{
|
||||
client: "cursor",
|
||||
path: ".cursor/mcp.json",
|
||||
@@ -92,7 +103,9 @@ for (const scenario of cases)
|
||||
);
|
||||
const config = join(home, scenario.path);
|
||||
await mkdir(dirname(config), { recursive: true });
|
||||
await writeFile(config, scenario.text);
|
||||
const original =
|
||||
"bytes" in scenario ? scenario.bytes : Buffer.from(scenario.text);
|
||||
await writeFile(config, original);
|
||||
const environment = {
|
||||
HOME: home,
|
||||
USERPROFILE: home,
|
||||
@@ -146,7 +159,7 @@ for (const scenario of cases)
|
||||
});
|
||||
if (!("syntax" in scenario))
|
||||
expect(uninstall.stdout).not.toContain("not valid JSON");
|
||||
expect(await readFile(config, "utf8")).toBe(scenario.text);
|
||||
expect(await readFile(config)).toEqual(original);
|
||||
expect(await readdir(dirname(config))).toEqual([
|
||||
scenario.path.split("/").at(-1),
|
||||
]);
|
||||
|
||||
@@ -1,13 +1,91 @@
|
||||
import { chmod, readFile, writeFile } from "node:fs/promises";
|
||||
import { createHash } from "node:crypto";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { parse as parseToml } from "smol-toml";
|
||||
|
||||
import { configureClientConfiguration } from "../../../src/application/SetupClientConfiguration.js";
|
||||
import {
|
||||
configureClientConfiguration,
|
||||
inspectClientConfiguration,
|
||||
} from "../../../src/application/SetupClientConfiguration.js";
|
||||
import { systemUninstallHost } from "../../../src/application/Uninstall.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
it("accepts a literal UTF-8 replacement character without changing its value", async () => {
|
||||
const root = await createTestTempDirectory("rea-client-config-utf8-");
|
||||
const configPath = join(root, "config.json");
|
||||
const original = Buffer.concat([
|
||||
Buffer.from('{"label":"'),
|
||||
Buffer.from("\uFFFD"),
|
||||
Buffer.from('"}'),
|
||||
]);
|
||||
await writeFile(configPath, original);
|
||||
const result = await configureClientConfiguration(
|
||||
{ name: "cursor", format: "json", configPath },
|
||||
{},
|
||||
["rea", "mcp"],
|
||||
);
|
||||
expect(result.status).toBe("configured");
|
||||
expect(await readFile(`${configPath}.rea.backup`)).toEqual(original);
|
||||
expect(JSON.parse(await readFile(configPath, "utf8")).label).toBe("\uFFFD");
|
||||
});
|
||||
|
||||
it("previews and creates a current recovery backup while preserving the first backup", async () => {
|
||||
const root = await createTestTempDirectory("rea-client-current-recovery-");
|
||||
const configPath = join(root, "config.json");
|
||||
const firstOriginal = '{"keep":"first"}\n';
|
||||
const currentOriginal = '{"keep":"current"}\n';
|
||||
const client = { name: "cursor", format: "json", configPath } as const;
|
||||
await writeFile(configPath, currentOriginal);
|
||||
await writeFile(`${configPath}.rea.backup`, firstOriginal);
|
||||
|
||||
const recoveryPath = `${configPath}.rea.backup.${createHash("sha256")
|
||||
.update(currentOriginal, "utf8")
|
||||
.digest("hex")}.recovery`;
|
||||
expect(await inspectClientConfiguration(client, {}, ["rea", "mcp"])).toEqual({
|
||||
status: "update",
|
||||
backupPath: recoveryPath,
|
||||
});
|
||||
|
||||
expect(
|
||||
await configureClientConfiguration(client, {}, ["rea", "mcp"]),
|
||||
).toEqual({ status: "configured", backupPath: recoveryPath });
|
||||
expect(await readFile(`${configPath}.rea.backup`, "utf8")).toBe(
|
||||
firstOriginal,
|
||||
);
|
||||
expect(await readFile(recoveryPath, "utf8")).toBe(currentOriginal);
|
||||
});
|
||||
|
||||
it("blocks configuration when the planned content-addressed backup is occupied", async () => {
|
||||
const root = await createTestTempDirectory("rea-client-recovery-conflict-");
|
||||
const configPath = join(root, "config.json");
|
||||
const firstOriginal = '{"keep":"first"}\n';
|
||||
const currentOriginal = '{"keep":"current"}\n';
|
||||
const client = { name: "cursor", format: "json", configPath } as const;
|
||||
await writeFile(configPath, currentOriginal);
|
||||
await writeFile(`${configPath}.rea.backup`, firstOriginal);
|
||||
const recoveryPath = `${configPath}.rea.backup.${createHash("sha256")
|
||||
.update(currentOriginal, "utf8")
|
||||
.digest("hex")}.recovery`;
|
||||
await writeFile(recoveryPath, "occupied by other data");
|
||||
|
||||
expect(
|
||||
await inspectClientConfiguration(client, {}, ["rea", "mcp"]),
|
||||
).toMatchObject({
|
||||
status: "invalid",
|
||||
remediation: expect.stringContaining(recoveryPath),
|
||||
});
|
||||
expect(
|
||||
await configureClientConfiguration(client, {}, ["rea", "mcp"]),
|
||||
).toEqual({ status: "failed", reason: "backup" });
|
||||
expect(await readFile(configPath, "utf8")).toBe(currentOriginal);
|
||||
expect(await readFile(`${configPath}.rea.backup`, "utf8")).toBe(
|
||||
firstOriginal,
|
||||
);
|
||||
expect(await readFile(recoveryPath, "utf8")).toBe("occupied by other data");
|
||||
});
|
||||
|
||||
describe("client configuration write failures", () => {
|
||||
it.skipIf(process.platform === "win32" || process.getuid?.() === 0).each([
|
||||
["json", configureClientConfiguration],
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
} from "../../../src/application/SetupHost.js";
|
||||
import { RegularFileCleanupFailure } from "../../../src/application/RegularFileRead.js";
|
||||
import { configureDetectedClients } from "../../../src/application/SetupClients.js";
|
||||
import { systemUninstallHost } from "../../../src/application/Uninstall.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
vi.mock("node:fs/promises", async (importOriginal) => {
|
||||
@@ -31,6 +32,61 @@ beforeEach(async () => {
|
||||
|
||||
afterEach(() => openMock.mockReset());
|
||||
|
||||
const holdReadHandle = (path: string, reason: string) => {
|
||||
const closeAttempts: object[] = [];
|
||||
let released = false;
|
||||
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 (!released) throw new Error(reason);
|
||||
await nativeClose();
|
||||
});
|
||||
return handle;
|
||||
});
|
||||
return {
|
||||
closeAttempts,
|
||||
release: () => {
|
||||
released = true;
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
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",
|
||||
format: "json",
|
||||
configPath: path,
|
||||
}),
|
||||
).toMatchObject({
|
||||
status: "failed",
|
||||
detail: expect.stringContaining("not valid UTF-8"),
|
||||
});
|
||||
expect(await readFile(path)).toEqual(original);
|
||||
expect(closeAttempts).toHaveLength(2);
|
||||
release();
|
||||
expect(await host.close?.()).toBeUndefined();
|
||||
expect(closeAttempts).toHaveLength(3);
|
||||
expect(closeAttempts[2]).toBe(closeAttempts[0]);
|
||||
} finally {
|
||||
release();
|
||||
await host.close?.();
|
||||
}
|
||||
});
|
||||
|
||||
describe("ZCode fallback cleanup ownership", () => {
|
||||
it.each(["preflight", "configure"])(
|
||||
"retains a failed ZCode fallback close during %s until host cleanup",
|
||||
@@ -49,19 +105,10 @@ describe("ZCode fallback cleanup ownership", () => {
|
||||
await mkdir(dirname(fallback), { recursive: true });
|
||||
const original = '{"mcpServers":{"other":{"command":"other"}}}\n';
|
||||
await writeFile(fallback, original);
|
||||
const closeAttempts: object[] = [];
|
||||
let allowClose = false;
|
||||
openMock.mockImplementation(async (...args) => {
|
||||
const handle = await actualFs.open(...args);
|
||||
if (String(args[0]) !== fallback) return handle;
|
||||
const nativeClose = handle.close.bind(handle);
|
||||
vi.spyOn(handle, "close").mockImplementation(async () => {
|
||||
closeAttempts.push(handle);
|
||||
if (!allowClose) throw new Error("held fallback handle");
|
||||
await nativeClose();
|
||||
});
|
||||
return handle;
|
||||
});
|
||||
const { closeAttempts, release } = holdReadHandle(
|
||||
fallback,
|
||||
"held fallback handle",
|
||||
);
|
||||
try {
|
||||
const action =
|
||||
operation === "preflight"
|
||||
@@ -79,12 +126,12 @@ describe("ZCode fallback cleanup ownership", () => {
|
||||
await expect(readFile(client.configPath)).rejects.toMatchObject({
|
||||
code: "ENOENT",
|
||||
});
|
||||
allowClose = true;
|
||||
release();
|
||||
expect(await host.close?.()).toBeUndefined();
|
||||
expect(closeAttempts).toHaveLength(3);
|
||||
expect(closeAttempts[2]).toBe(closeAttempts[0]);
|
||||
} finally {
|
||||
allowClose = true;
|
||||
release();
|
||||
await host.close?.();
|
||||
}
|
||||
},
|
||||
@@ -92,83 +139,87 @@ describe("ZCode fallback cleanup ownership", () => {
|
||||
});
|
||||
|
||||
describe("setup client configuration cleanup ownership", () => {
|
||||
it("stops client configuration and retries the same alignment handle from host close", async () => {
|
||||
const home = await createTestTempDirectory("rea-setup-config-close-");
|
||||
const environment = {
|
||||
HOME: home,
|
||||
XDG_CONFIG_HOME: join(home, "xdg"),
|
||||
};
|
||||
const host = systemSetupHost(
|
||||
{ platform: "linux", homeDirectory: home } as DoctorHost,
|
||||
environment,
|
||||
);
|
||||
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 });
|
||||
const original = Buffer.from('{"servers": {"other": {}}}\n');
|
||||
await writeFile(client.configPath, original);
|
||||
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 home = await createTestTempDirectory("rea-setup-config-close-");
|
||||
const environment = {
|
||||
HOME: home,
|
||||
XDG_CONFIG_HOME: join(home, "xdg"),
|
||||
};
|
||||
const host = systemSetupHost(
|
||||
{ platform: "linux", homeDirectory: home } as DoctorHost,
|
||||
environment,
|
||||
);
|
||||
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 });
|
||||
await writeFile(client.configPath, original);
|
||||
|
||||
const closeAttempts: object[] = [];
|
||||
let allowClose = false;
|
||||
openMock.mockImplementation(async (...args) => {
|
||||
const handle = await actualFs.open(...args);
|
||||
if (String(args[0]) !== client.configPath) return handle;
|
||||
const nativeClose = handle.close.bind(handle);
|
||||
vi.spyOn(handle, "close").mockImplementation(async () => {
|
||||
closeAttempts.push(handle);
|
||||
if (!allowClose) throw new Error("test holds the config handle open");
|
||||
await nativeClose();
|
||||
});
|
||||
return handle;
|
||||
});
|
||||
const configure = vi.spyOn(host, "configureClient");
|
||||
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], {}, [
|
||||
"rea",
|
||||
"mcp",
|
||||
])
|
||||
.then((detectedClients) =>
|
||||
configureDetectedClients({
|
||||
host,
|
||||
detectedClients,
|
||||
providerEnvironment: {},
|
||||
command: ["rea", "mcp"],
|
||||
clients: {},
|
||||
appliedActions: [],
|
||||
}),
|
||||
try {
|
||||
const failure = await filterClientsNeedingConfigure(
|
||||
host,
|
||||
[client],
|
||||
{},
|
||||
["rea", "mcp"],
|
||||
)
|
||||
.then(
|
||||
() => undefined,
|
||||
(cause: unknown) => cause,
|
||||
);
|
||||
expect(failure).toBeInstanceOf(ConfigurationError);
|
||||
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(await readFile(client.configPath)).toEqual(original);
|
||||
.then((detectedClients) =>
|
||||
configureDetectedClients({
|
||||
host,
|
||||
detectedClients,
|
||||
providerEnvironment: {},
|
||||
command: ["rea", "mcp"],
|
||||
clients: {},
|
||||
appliedActions: [],
|
||||
}),
|
||||
)
|
||||
.then(
|
||||
() => undefined,
|
||||
(cause: unknown) => cause,
|
||||
);
|
||||
expect(failure).toBeInstanceOf(ConfigurationError);
|
||||
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(await readFile(client.configPath)).toEqual(original);
|
||||
|
||||
allowClose = true;
|
||||
const close = host.close;
|
||||
if (close === undefined) throw new Error("Setup host close is missing");
|
||||
expect(await close()).toBeUndefined();
|
||||
expect(closeAttempts).toHaveLength(3);
|
||||
expect(closeAttempts[2]).toBe(closeAttempts[0]);
|
||||
} finally {
|
||||
allowClose = true;
|
||||
await host.close?.();
|
||||
}
|
||||
});
|
||||
release();
|
||||
expect(await host.close?.()).toBeUndefined();
|
||||
expect(closeAttempts).toHaveLength(3);
|
||||
expect(closeAttempts[2]).toBe(closeAttempts[0]);
|
||||
} finally {
|
||||
release();
|
||||
await host.close?.();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it("waits for an admitted configuration read and rejects later admissions", async () => {
|
||||
const home = await createTestTempDirectory("rea-setup-config-inflight-");
|
||||
|
||||
@@ -0,0 +1,325 @@
|
||||
import { open, readFile } from "node:fs/promises";
|
||||
import { createHash } from "node:crypto";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { afterEach, expect, it, onTestFinished, vi } from "vitest";
|
||||
|
||||
const state = vi.hoisted(() => ({
|
||||
readbackFailed: false,
|
||||
rejectRestore: false,
|
||||
rejectRemove: false,
|
||||
removeCopiedRecovery: false,
|
||||
initialCleanupFailure: undefined as unknown,
|
||||
readbackCleanupFailure: undefined as unknown,
|
||||
}));
|
||||
|
||||
afterEach(() => {
|
||||
state.readbackFailed = false;
|
||||
state.rejectRestore = false;
|
||||
state.rejectRemove = false;
|
||||
state.removeCopiedRecovery = false;
|
||||
state.initialCleanupFailure = undefined;
|
||||
state.readbackCleanupFailure = undefined;
|
||||
});
|
||||
|
||||
vi.mock("node:fs/promises", async (importOriginal) => {
|
||||
const original = await importOriginal<typeof import("node:fs/promises")>();
|
||||
return {
|
||||
...original,
|
||||
rm: (
|
||||
...arguments_: Parameters<typeof original.rm>
|
||||
): ReturnType<typeof original.rm> => {
|
||||
if (state.rejectRemove && state.readbackFailed)
|
||||
return Promise.reject(new Error("injected restore remove failure"));
|
||||
return original.rm(...arguments_);
|
||||
},
|
||||
writeFile: (
|
||||
...arguments_: Parameters<typeof original.writeFile>
|
||||
): ReturnType<typeof original.writeFile> => {
|
||||
if (state.rejectRestore && state.readbackFailed)
|
||||
return Promise.reject(new Error("injected restore write failure"));
|
||||
return original.writeFile(...arguments_);
|
||||
},
|
||||
copyFile: async (
|
||||
...arguments_: Parameters<typeof original.copyFile>
|
||||
): Promise<void> => {
|
||||
await original.copyFile(...arguments_);
|
||||
const destination = arguments_[1];
|
||||
if (
|
||||
state.removeCopiedRecovery &&
|
||||
typeof destination === "string" &&
|
||||
destination.endsWith(".recovery")
|
||||
)
|
||||
await original.rm(destination);
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("write-file-atomic", async (importOriginal) => {
|
||||
const original = await importOriginal<{
|
||||
default: typeof import("write-file-atomic");
|
||||
}>();
|
||||
return {
|
||||
...original,
|
||||
default: async (...arguments_: Parameters<typeof original.default>) => {
|
||||
if (state.initialCleanupFailure !== undefined)
|
||||
throw new Error("unexpected config write before initial read");
|
||||
const result = await original.default(...arguments_);
|
||||
state.readbackFailed = true;
|
||||
return result;
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("../../src/application/RegularFileRead.js", async (importOriginal) => {
|
||||
const original =
|
||||
await importOriginal<
|
||||
typeof import("../../src/application/RegularFileRead.js")
|
||||
>();
|
||||
return {
|
||||
...original,
|
||||
readRegularFileText: (
|
||||
...arguments_: Parameters<typeof original.readRegularFileText>
|
||||
) =>
|
||||
state.initialCleanupFailure !== undefined
|
||||
? Promise.reject(state.initialCleanupFailure)
|
||||
: state.readbackFailed && state.readbackCleanupFailure !== undefined
|
||||
? Promise.reject(state.readbackCleanupFailure)
|
||||
: state.readbackFailed
|
||||
? Promise.reject(new Error("injected readback failure"))
|
||||
: original.readRegularFileText(...arguments_),
|
||||
};
|
||||
});
|
||||
|
||||
import { configureClientConfiguration } from "../../src/application/SetupClientConfiguration.js";
|
||||
import { RegularFileCleanupFailure } from "../../src/application/RegularFileRead.js";
|
||||
import { OwnedFileHandle } from "../../src/filesystem/OwnedFileHandle.js";
|
||||
import type { DoctorHost } from "../../src/application/Doctor.js";
|
||||
import { systemSetupHost } from "../../src/application/SetupHost.js";
|
||||
import { ConfigurationError } from "../../src/domain/configurationErrors.js";
|
||||
import { createTestTempDirectory } from "../fixtures/temporaryDirectory.js";
|
||||
|
||||
const ownReadHandle = async (path: string) => {
|
||||
const owner = new OwnedFileHandle(await open(path, "r"));
|
||||
onTestFinished(() => owner.close());
|
||||
return owner;
|
||||
};
|
||||
|
||||
it("reports a failed config rollback and retains its backup path", async () => {
|
||||
state.readbackFailed = false;
|
||||
state.rejectRestore = false;
|
||||
state.rejectRemove = false;
|
||||
state.initialCleanupFailure = undefined;
|
||||
state.readbackCleanupFailure = undefined;
|
||||
const root = await createTestTempDirectory("rea-config-rollback-");
|
||||
const path = join(root, "client.json");
|
||||
const original = '{"keep":true}\n';
|
||||
await import("node:fs/promises").then(({ writeFile }) =>
|
||||
writeFile(path, original),
|
||||
);
|
||||
state.rejectRestore = true;
|
||||
|
||||
const result = await configureClientConfiguration(
|
||||
{ name: "cursor", configPath: path, format: "json" },
|
||||
{},
|
||||
["rea", "mcp"],
|
||||
);
|
||||
|
||||
expect(result).toEqual({
|
||||
status: "failed",
|
||||
reason: "rollback",
|
||||
backupPath: `${path}.rea.backup`,
|
||||
failure: {
|
||||
kind: "restore",
|
||||
path,
|
||||
detail: "injected restore write failure",
|
||||
},
|
||||
});
|
||||
expect(await readFile(`${path}.rea.backup`, "utf8")).toBe(original);
|
||||
expect(JSON.parse(await readFile(path, "utf8"))).toMatchObject({
|
||||
mcpServers: { rea: { command: "rea", args: ["mcp"] } },
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves the first backup and reports a verified backup of the current original", async () => {
|
||||
state.readbackFailed = false;
|
||||
state.rejectRestore = false;
|
||||
state.rejectRemove = false;
|
||||
state.initialCleanupFailure = undefined;
|
||||
state.readbackCleanupFailure = undefined;
|
||||
const root = await createTestTempDirectory("rea-config-stale-backup-");
|
||||
const path = join(root, "client.json");
|
||||
const firstOriginal = '{"keep":"first"}\n';
|
||||
const currentOriginal = '{"keep":"current"}\n';
|
||||
await import("node:fs/promises").then(async ({ writeFile }) => {
|
||||
await writeFile(path, currentOriginal);
|
||||
await writeFile(`${path}.rea.backup`, firstOriginal);
|
||||
});
|
||||
state.rejectRestore = true;
|
||||
|
||||
const result = await configureClientConfiguration(
|
||||
{ name: "cursor", configPath: path, format: "json" },
|
||||
{},
|
||||
["rea", "mcp"],
|
||||
);
|
||||
state.rejectRestore = false;
|
||||
|
||||
const recoveryPath = `${path}.rea.backup.${createHash("sha256")
|
||||
.update(currentOriginal, "utf8")
|
||||
.digest("hex")}.recovery`;
|
||||
expect(result).toMatchObject({
|
||||
status: "failed",
|
||||
reason: "rollback",
|
||||
backupPath: recoveryPath,
|
||||
failure: {
|
||||
kind: "restore",
|
||||
path,
|
||||
detail: "injected restore write failure",
|
||||
},
|
||||
});
|
||||
expect(await readFile(`${path}.rea.backup`, "utf8")).toBe(firstOriginal);
|
||||
expect(await readFile(recoveryPath, "utf8")).toBe(currentOriginal);
|
||||
});
|
||||
|
||||
it("does not write config when a recovery copy disappears before verification", async () => {
|
||||
state.readbackFailed = false;
|
||||
state.rejectRestore = false;
|
||||
state.rejectRemove = false;
|
||||
state.removeCopiedRecovery = false;
|
||||
state.initialCleanupFailure = undefined;
|
||||
state.readbackCleanupFailure = undefined;
|
||||
const root = await createTestTempDirectory("rea-config-vanished-recovery-");
|
||||
const path = join(root, "client.json");
|
||||
const firstOriginal = '{"keep":"first"}\n';
|
||||
const currentOriginal = '{"keep":"current"}\n';
|
||||
await import("node:fs/promises").then(async ({ writeFile }) => {
|
||||
await writeFile(path, currentOriginal);
|
||||
await writeFile(`${path}.rea.backup`, firstOriginal);
|
||||
});
|
||||
state.removeCopiedRecovery = true;
|
||||
|
||||
const result = await configureClientConfiguration(
|
||||
{ name: "cursor", configPath: path, format: "json" },
|
||||
{},
|
||||
["rea", "mcp"],
|
||||
);
|
||||
state.removeCopiedRecovery = false;
|
||||
|
||||
expect(result).toEqual({ status: "failed", reason: "backup" });
|
||||
expect(await readFile(path, "utf8")).toBe(currentOriginal);
|
||||
expect(await readFile(`${path}.rea.backup`, "utf8")).toBe(firstOriginal);
|
||||
});
|
||||
|
||||
it("does not roll back or remove config when its initial read cleanup fails", async () => {
|
||||
state.readbackFailed = false;
|
||||
state.rejectRestore = false;
|
||||
state.rejectRemove = false;
|
||||
state.readbackCleanupFailure = undefined;
|
||||
const root = await createTestTempDirectory("rea-config-initial-cleanup-");
|
||||
const path = join(root, "client.json");
|
||||
const original = '{"keep":true}\n';
|
||||
await import("node:fs/promises").then(({ writeFile }) =>
|
||||
writeFile(path, original),
|
||||
);
|
||||
const failure = new RegularFileCleanupFailure(
|
||||
path,
|
||||
await ownReadHandle(path),
|
||||
{ kind: "completed", value: original },
|
||||
new Error("injected initial close failure"),
|
||||
);
|
||||
state.initialCleanupFailure = failure;
|
||||
|
||||
await expect(
|
||||
configureClientConfiguration(
|
||||
{ name: "cursor", configPath: path, format: "json" },
|
||||
{},
|
||||
["rea", "mcp"],
|
||||
),
|
||||
).rejects.toBe(failure);
|
||||
expect(await readFile(path, "utf8")).toBe(original);
|
||||
});
|
||||
|
||||
it("reports first-run rollback removal failure without a backup", async () => {
|
||||
state.readbackFailed = false;
|
||||
state.rejectRestore = false;
|
||||
state.rejectRemove = false;
|
||||
state.initialCleanupFailure = undefined;
|
||||
state.readbackCleanupFailure = undefined;
|
||||
const root = await createTestTempDirectory("rea-config-first-run-rollback-");
|
||||
const path = join(root, "client.json");
|
||||
state.rejectRemove = true;
|
||||
|
||||
const result = await configureClientConfiguration(
|
||||
{ name: "cursor", configPath: path, format: "json" },
|
||||
{},
|
||||
["rea", "mcp"],
|
||||
);
|
||||
state.rejectRemove = false;
|
||||
|
||||
expect(result).toMatchObject({
|
||||
status: "failed",
|
||||
reason: "rollback",
|
||||
failure: {
|
||||
kind: "restore",
|
||||
path,
|
||||
detail: "injected restore remove failure",
|
||||
},
|
||||
});
|
||||
expect(result).not.toHaveProperty("backupPath");
|
||||
expect(JSON.parse(await readFile(path, "utf8"))).toMatchObject({
|
||||
mcpServers: { rea: { command: "rea", args: ["mcp"] } },
|
||||
});
|
||||
});
|
||||
|
||||
it("retains readback cleanup ownership when rollback also fails", async () => {
|
||||
state.readbackFailed = false;
|
||||
state.rejectRestore = false;
|
||||
state.rejectRemove = false;
|
||||
state.initialCleanupFailure = undefined;
|
||||
const root = await createTestTempDirectory("rea-config-readback-cleanup-");
|
||||
const path = join(root, "client.json");
|
||||
const original = '{"keep":true}\n';
|
||||
await import("node:fs/promises").then(({ writeFile }) =>
|
||||
writeFile(path, original),
|
||||
);
|
||||
const owner = await ownReadHandle(path);
|
||||
const cleanupFailure = new RegularFileCleanupFailure(
|
||||
path,
|
||||
owner,
|
||||
{ kind: "completed", value: "" },
|
||||
new Error("injected readback close failure"),
|
||||
);
|
||||
state.readbackCleanupFailure = cleanupFailure;
|
||||
state.rejectRestore = true;
|
||||
|
||||
const host = systemSetupHost(
|
||||
{ platform: "linux", homeDirectory: root } as DoctorHost,
|
||||
{ HOME: root },
|
||||
);
|
||||
let caught: unknown;
|
||||
try {
|
||||
await host.configureClient(
|
||||
{ name: "cursor", configPath: path, format: "json" },
|
||||
{},
|
||||
["rea", "mcp"],
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
caught = cause;
|
||||
} finally {
|
||||
await host.close?.();
|
||||
}
|
||||
|
||||
if (!(caught instanceof ConfigurationError)) throw caught;
|
||||
expect(caught.message).toContain("injected restore write failure");
|
||||
expect(caught.message).toContain(`${path}.rea.backup`);
|
||||
const cleanupOwnerError = caught.cause;
|
||||
if (!(cleanupOwnerError instanceof RegularFileCleanupFailure))
|
||||
throw new Error("Configuration failure lost its read owner");
|
||||
expect(cleanupOwnerError).toMatchObject({
|
||||
path,
|
||||
outcome: { kind: "completed", value: "" },
|
||||
cleanupCause: expect.any(AggregateError),
|
||||
});
|
||||
expect(cleanupOwnerError.owner).toBe(owner);
|
||||
expect(await readFile(`${path}.rea.backup`, "utf8")).toBe(original);
|
||||
});
|
||||
Reference in New Issue
Block a user