Files
reverse-engineering-anything/tests/acceptance/setup/clientConfigurationDiagnosticsCli.test.ts
Ysopwnableandgensokyo-dev a8fa92107c test(setup): cover shared Copilot CLI project configuration (#15275)
Exercise owned Copilot CLI removal and backup in the shared project
MCP file. Assert the winning Mastra Code registration in doctor when
multiple clients report the same shared file.

Follow-up to #15230.

Assisted-by: Kogasa (gensokyo-skills:kogasa-surprise-testing)
Co-authored-by: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com>
2026-12-01 01:07:54 +08:00

615 lines
17 KiB
TypeScript

import {
chmod,
mkdir,
readFile,
readdir,
rm,
symlink,
writeFile,
} from "node:fs/promises";
import { dirname, join } from "node:path";
import { afterAll, beforeAll, beforeEach, expect } from "vitest";
import { isRecord } from "../../../src/kernel/isRecord.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { cliTest } from "../../support/cli/cliFixture.js";
import {
createTestWorkspace,
removeTestWorkspace,
} from "../../support/workspace/workspaceFixture.js";
let sharedDiagnosticHome = "";
beforeAll(async () => {
sharedDiagnosticHome = (
await createTestWorkspace("rea-client-config-diagnostic-")
).root;
});
beforeEach(async () => {
for (const entry of await readdir(sharedDiagnosticHome)) {
await rm(join(sharedDiagnosticHome, entry), {
recursive: true,
force: true,
});
}
});
afterAll(async () => {
if (sharedDiagnosticHome !== "") {
await removeTestWorkspace(sharedDiagnosticHome);
}
});
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",
text: "[]",
diagnostic: "The configuration root must be an object",
},
{
client: "cursor",
path: ".cursor/mcp.json",
text: "null",
diagnostic: "The configuration root must be an object",
},
{
client: "cursor",
path: ".cursor/mcp.json",
text: '{"mcpServers":null,"keep":1}',
diagnostic: '"mcpServers" must be an object',
},
{
client: "cursor",
path: ".cursor/mcp.json",
text: '{"mcpServers":"x","keep":1}',
diagnostic: '"mcpServers" must be an object',
},
{
client: "pi",
path: ".pi/agent/mcp.json",
text: '{"mcpServers":[]}',
diagnostic: '"mcpServers" must be an object',
},
{
client: "codex",
path: ".codex/config.toml",
text: 'mcp_servers = "x"\n',
diagnostic: '"mcp_servers" must be an object',
},
{
client: "opencode",
path: ".config/opencode/opencode.json",
text: '{"mcp":{"servers":null}}',
diagnostic: '"mcp.servers" must be an object',
},
{
client: "hermes",
path: ".hermes/config.yaml",
text: "- item\n",
diagnostic: "The configuration root must be an object",
},
{
client: "hermes",
path: ".hermes/config.yaml",
text: "mcp_servers: null\nkeep: 1\n",
diagnostic: '"mcp_servers" must be an object',
},
{
client: "cursor",
path: ".cursor/mcp.json",
text: "not-json",
diagnostic: "Configuration is not valid JSONC and was not changed",
syntax: "JSONC",
},
{
// Pi loads mcp.json with strict JSON.parse, so REA's reader admits JSON only.
client: "pi",
path: ".pi/agent/mcp.json",
text: '{"mcpServers":{},}',
diagnostic: "Configuration is not valid JSON and was not changed",
syntax: "JSON",
},
{
client: "mastracode",
path: ".mastracode/mcp.json",
text: '{"mcpServers":{},}',
diagnostic: "Configuration is not valid JSON and was not changed",
syntax: "JSON",
},
{
client: "codex",
path: ".codex/config.toml",
text: "[mcp_servers\n",
diagnostic: "Configuration is not valid TOML and was not changed",
syntax: "TOML",
},
{
client: "hermes",
path: ".hermes/config.yaml",
text: "mcp_servers: [\n",
diagnostic: "Configuration is not valid YAML",
syntax: "YAML",
},
{
client: "dsh",
path: ".dsh/cordis.patch.yml",
text: "- insert: [\n",
diagnostic: "Invalid or unsupported Cordis YAML",
syntax: "YAML",
},
] as const;
for (const scenario of cases)
cliTest(
`setup and uninstall explain ${scenario.client} configuration ${scenario.text}`,
async ({ cli }) => {
const home = sharedDiagnosticHome;
const config = join(home, scenario.path);
await mkdir(dirname(config), { recursive: true });
const original =
"bytes" in scenario ? scenario.bytes : Buffer.from(scenario.text);
await writeFile(config, original);
const environment = {
HOME: home,
USERPROFILE: home,
XDG_CONFIG_HOME: join(home, ".config"),
HERMES_HOME: join(home, ".hermes"),
DSH_HOME: join(home, ".dsh"),
};
const setup = await cli.run({
arguments: [
"setup",
"--client",
scenario.client,
"--skill=false",
"--yes",
"--json",
],
cwd: home,
environment,
});
expect(setup.exitCode).toBe(1);
expect(setup.json).toMatchObject({
status: "needs_human",
plannedActions: [],
appliedActions: [],
});
if ("syntax" in scenario) {
expect(setup.json).toMatchObject({
remediation: expect.stringMatching(/\S/u),
});
if (scenario.syntax === "JSONC")
expect(setup.stdout).toContain("Invalid JSON/JSONC");
} else {
expect(setup.json).toMatchObject({
remediation: expect.stringContaining(scenario.diagnostic),
});
expect(setup.stdout).not.toContain("invalid_type");
}
const uninstall = await cli.run({
arguments: ["uninstall", "--json"],
cwd: home,
environment,
});
expect(uninstall.exitCode).toBe(1);
expect(uninstall.json).toMatchObject({
status: "failed",
items: expect.arrayContaining([
expect.objectContaining({
name: scenario.client,
status: "failed",
detail: expect.stringContaining(scenario.diagnostic),
}),
]),
});
if (!("syntax" in scenario))
expect(uninstall.stdout).not.toContain("not valid JSON");
expect(Buffer.compare(await readFile(config), original)).toBe(0);
expect(await readdir(dirname(config))).toEqual([
scenario.path.split("/").at(-1),
]);
},
);
cliTest.skipIf(process.platform === "win32" || process.getuid?.() === 0)(
"doctor reports an unreadable configuration symlink without changing it",
async ({ cli }) => {
const home = await createTestTempDirectory(
"rea-doctor-denied-registration-",
);
const moduleCache = await createTestTempDirectory(
"rea-doctor-swift-cache-",
);
const locked = join(home, "owned-denied");
const target = join(locked, "client.json");
await mkdir(locked);
const original =
'{"mcpServers":{"rea":{"command":"rea","args":["mcp"]}}}\n';
await writeFile(target, original);
const config = join(home, ".claude.json");
await symlink(target, config);
await chmod(locked, 0);
try {
const result = await cli.run({
arguments: [
"doctor",
"--client",
"claude_code",
"--skill=false",
"--json",
],
cwd: home,
environment: {
HOME: home,
USERPROFILE: home,
XDG_CONFIG_HOME: join(home, ".config"),
REA_DARWIN_MODULE_CACHE_PATH: moduleCache,
},
});
expect(result.exitCode).toBe(1);
expect(result.json).toMatchObject({
healthy: false,
identity: {
registrations: [
expect.objectContaining({
client: "claude_code",
config_path: config,
state: "invalid",
command: [],
}),
],
},
});
} finally {
await chmod(locked, 0o700);
}
expect(await readFile(target, "utf8")).toBe(original);
expect((await readdir(home)).sort()).toEqual([
".claude.json",
"owned-denied",
]);
},
);
cliTest(
"doctor reports unknown provider readiness for a malformed selected registration",
async ({ cli }) => {
const home = await createTestTempDirectory(
"rea-doctor-unknown-registration-",
);
const config = join(home, ".config/opencode/opencode.json");
await mkdir(dirname(config), { recursive: true });
await writeFile(config, "not JSON");
const result = await cli.run({
arguments: [
"doctor",
"--client",
"opencode",
"--provider",
"ghidra",
"--json",
],
cwd: home,
environment: {
HOME: home,
USERPROFILE: home,
XDG_CONFIG_HOME: join(home, ".config"),
GHIDRA_INSTALL_DIR: join(home, "ghidra"),
},
});
expect(result.exitCode).toBe(1);
expect(result.json).toMatchObject({
providerInspections: expect.arrayContaining([
expect.objectContaining({
id: "ghidra",
configured: null,
available: null,
}),
]),
scope_checks: expect.arrayContaining([
expect.objectContaining({
name: "ghidra",
classification: "unknown",
ok: false,
}),
]),
});
},
);
cliTest(
"doctor attributes the Mastra Code registration to the winning project file",
async ({ cli, processes }) => {
const home = await createTestTempDirectory("rea-doctor-mastra-home-");
const project = await createTestTempDirectory("rea-doctor-mastra-project-");
const userConfig = join(home, ".mastracode", "mcp.json");
const sharedProjectConfig = join(project, ".mcp.json");
const nativeProjectConfig = join(project, ".mastracode", "mcp.json");
const writeRegistration = async (path: string, command: string) => {
await mkdir(dirname(path), { recursive: true });
await writeFile(
path,
JSON.stringify({ mcpServers: { rea: { command } } }),
);
};
const doctor = (
cwd = project,
options: readonly string[] = [],
environment: NodeJS.ProcessEnv = {},
) =>
cli.run({
arguments: [
"doctor",
"--client",
"mastracode",
"--skill=false",
"--json",
...options,
],
cwd,
environment: {
HOME: home,
USERPROFILE: home,
XDG_CONFIG_HOME: join(home, ".config"),
...environment,
},
});
const expectRegistration = (
json: unknown,
configPath: string,
command: string,
scope: "project" | "user",
) => {
const registrations =
isRecord(json) &&
isRecord(json.identity) &&
Array.isArray(json.identity.registrations)
? json.identity.registrations
: [];
expect(
registrations.filter(
(row: unknown) => isRecord(row) && row.client === "mastracode",
),
).toMatchObject([
{
client: "mastracode",
config_path: configPath,
command: [command],
scope,
},
]);
};
// The entire server row is replaced, so a lower HTTP URL cannot turn the
// project's stdio registration into an ambiguous transport.
await mkdir(dirname(userConfig), { recursive: true });
await writeFile(
userConfig,
JSON.stringify({
mcpServers: { rea: { url: "https://example.invalid/mcp" } },
}),
);
await writeRegistration(sharedProjectConfig, "shared-project-server");
expectRegistration(
(await doctor()).json,
sharedProjectConfig,
"shared-project-server",
"project",
);
await writeRegistration(nativeProjectConfig, "native-project-server");
expectRegistration(
(await doctor()).json,
nativeProjectConfig,
"native-project-server",
"project",
);
const init = await processes.run("git", ["init", "--quiet"], {
cwd: project,
});
expect(init.exitCode, init.stderr).toBe(0);
const nested = join(project, "subdirectory");
await mkdir(nested);
await writeFile(
userConfig,
JSON.stringify({
mcpServers: {
rea: {
command: "user-server",
env: { GHIDRA_INSTALL_DIR: join(home, "missing-ghidra") },
},
},
}),
);
const { json: nestedReport } = await doctor(nested, [
"--provider",
"ghidra",
]);
expectRegistration(
nestedReport,
nativeProjectConfig,
"native-project-server",
"project",
);
if (
!isRecord(nestedReport) ||
!Array.isArray(nestedReport.providerInspections)
)
throw new Error("Doctor did not report provider inspections");
const ghidra = nestedReport.providerInspections.find(
(inspection: unknown) =>
isRecord(inspection) && inspection.id === "ghidra",
);
expect(ghidra).toHaveProperty("configured", null);
expect(ghidra).toHaveProperty("available", null);
expect(ghidra).toHaveProperty(
"checks.0.code",
"project_provider_settings_unapproved",
);
const { json: disabledReport } = await doctor(
nested,
["--provider", "ghidra"],
{
MASTRACODE_DISABLE_MCP: "1",
GHIDRA_INSTALL_DIR: join(home, "missing-terminal-ghidra"),
},
);
expect(disabledReport).toMatchObject({
identity: {
registrations: expect.arrayContaining([
expect.objectContaining({
client: "mastracode",
config_path: nativeProjectConfig,
scope: "project",
state: "stale",
remediation: expect.stringContaining("MASTRACODE_DISABLE_MCP"),
}),
]),
},
providerInspections: expect.arrayContaining([
expect.objectContaining({
id: "ghidra",
checks: expect.not.arrayContaining([
expect.objectContaining({
code: "project_provider_settings_unapproved",
}),
]),
}),
]),
});
// The same file can be both the user source and the highest-priority
// project source when Mastra Code is started in the home directory.
await writeRegistration(join(home, ".mcp.json"), "home-project-server");
expectRegistration(
(await doctor(home)).json,
userConfig,
"user-server",
"user",
);
await rm(sharedProjectConfig);
await writeFile(nativeProjectConfig, JSON.stringify({ mcpServers: {} }));
expectRegistration(
(await doctor()).json,
userConfig,
"user-server",
"user",
);
},
);
cliTest(
"doctor automatically discovers Mastra Code from its native project file",
async ({ cli }) => {
const home = await createTestTempDirectory("rea-doctor-mastra-home-");
const project = await createTestTempDirectory("rea-doctor-mastra-project-");
const doctor = () =>
cli.run({
arguments: ["doctor", "--skill=false", "--json"],
cwd: project,
environment: {
HOME: home,
USERPROFILE: home,
XDG_CONFIG_HOME: join(home, ".config"),
},
});
await writeFile(
join(project, ".mcp.json"),
JSON.stringify({ mcpServers: { rea: { command: "shared-server" } } }),
);
expect((await doctor()).json).toMatchObject({
identity: {
registrations: expect.not.arrayContaining([
expect.objectContaining({ client: "mastracode" }),
]),
},
});
const nativeConfig = join(project, ".mastracode", "mcp.json");
await mkdir(dirname(nativeConfig));
await writeFile(
nativeConfig,
JSON.stringify({ mcpServers: { rea: { command: "native-server" } } }),
);
expect((await doctor()).json).toMatchObject({
identity: {
registrations: expect.arrayContaining([
expect.objectContaining({
client: "mastracode",
config_path: nativeConfig,
command: ["native-server"],
scope: "project",
}),
]),
},
});
},
);
cliTest.for([
{ scope: "system settings", filename: "system.json" },
{ scope: "system defaults", filename: "defaults.json" },
])(
"doctor discovers a Qwen registration present only in $scope",
async ({ filename }, { cli }) => {
const home = sharedDiagnosticHome;
const system = join(home, "system.json");
const defaults = join(home, "defaults.json");
const path = join(home, filename);
await writeFile(
path,
JSON.stringify({
mcpServers: {
rea: {
command: "npx",
args: ["-y", "rea-agents@1.0.0", "mcp"],
env: { REA_KUNA_JOBS: 42 },
},
},
}),
);
const result = await cli.run({
arguments: ["doctor", "--skill=false", "--json"],
cwd: home,
environment: {
HOME: home,
USERPROFILE: home,
XDG_CONFIG_HOME: join(home, ".config"),
QWEN_HOME: join(home, ".qwen"),
QWEN_CODE_SYSTEM_SETTINGS_PATH: system,
QWEN_CODE_SYSTEM_DEFAULTS_PATH: defaults,
},
});
expect(result.json).toMatchObject({
identity: {
registrations: expect.arrayContaining([
expect.objectContaining({
client: "qwen_code",
config_path: path,
state: "invalid",
command_identity: "owned",
remediation: expect.stringContaining("REA_KUNA_JOBS"),
}),
]),
},
});
},
);