feat(setup)!: expand agent integrations and verify updates (#577)

* feat(setup)!: expand agent integrations and simplify onboarding

Add native configuration formats for OpenCode, Antigravity, GitHub Copilot
CLI, VS Code, and Devin. Preserve JSONC comments and unrelated settings
while making setup and uninstall ownership-aware and idempotent.

Select agent targets before planning, separate discovery from intent, and
keep agent-only setup independent of optional provider prerequisites.
Cover configuration boundaries and interactive behavior in packaged checks.

BREAKING CHANGE: unscoped setup refreshes only existing REA-owned
registrations. Use --all-detected to configure every detected client.
Setup JSON contains a compact doctor summary; use rea doctor for full
diagnostics. Cancellation and successful dry runs now exit successfully.

* feat(cli)!: replace upgrade with verified updates

Resolve an exact release through npm's configured registry, update only the
identified installation, and verify its new executable before reporting success.
Return a read-only maintenance plan for existing enabled REA integrations.

BREAKING CHANGE: replace rea upgrade with rea update; no alias is retained.
Successful update JSON uses status "updated", reports the verified installed
version, and returns an unapplied maintenance plan instead of opening setup.
This commit is contained in:
morluto
2026-10-05 23:06:19 +08:00
committed by GitHub
parent b225b0f64b
commit 6256b68666
51 changed files with 3951 additions and 1378 deletions
+193 -196
View File
@@ -4,11 +4,17 @@ import { promisify } from "node:util";
import { spawn } from "@lydell/node-pty";
import { describe, expect, it } from "vitest";
import { z } from "zod";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
const execute = promisify(execFile);
const decisionMarker = "REA_SETUP_DECISION:";
const decisionSchema = z.object({
approved: z.boolean(),
selectedActionIds: z.array(z.string()),
cancelled: z.boolean().optional(),
});
const actions = [
{
@@ -40,234 +46,222 @@ const actions = [
},
] as const;
const clientStates = [
{
client: {
name: "codex",
format: "toml",
configPath: [".codex", "config.toml"],
marker: [".codex"],
},
detected: true,
configured: false,
status: "needs_configuration",
},
{
client: {
name: "opencode",
format: "opencode",
configPath: [".config", "opencode", "opencode.json"],
marker: [".config", "opencode"],
},
detected: false,
configured: false,
status: "missing",
},
] as const;
const agentActions = actions.filter(({ kind }) => kind !== "install_hopper");
describe("interactive setup journey", () => {
it("leads with value, a compact detected-target summary, and durable key help", async () => {
const result = await runJourney([
step("What should REA set up?", "\u0003"),
]);
expect(result.output).toContain(
"Understand local apps and binaries from your coding agent.",
);
expect(result.output).toContain(
"Trace how a feature works with local evidence.",
);
expect(result.output).toContain("Found 1 supported agent");
expect(result.output).toContain("Codex");
expect(result.output).toContain("Hopper deep-analysis provider (provider)");
expect(result.output).toContain(
"Agent integration (MCP + guided workflow)",
);
expect(result.output).toContain(
"Keys: ↑/↓ navigate · Space toggle · Enter confirm · Ctrl-C cancel",
);
expect(result.decision.approved).toBe(false);
});
it("allows deselecting the pre-selected agent integration to opt out", async () => {
const result = await runJourney([step("What should REA set up?", " \r")]);
expect(result.output).toContain(
"Agent integration (MCP + guided workflow)",
);
expect(result.output).not.toContain(
"REA reverse-engineering skill (skill)",
);
expect(result.output).toContain("Hopper deep-analysis provider (provider)");
expect(result.output).not.toContain("Ready to review");
expect(result.output).toContain("Nothing selected. No changes were made.");
expect(result.decision).toEqual({
approved: false,
selectedActionIds: [],
});
});
it("pre-selects agent integration and proceeds to the agent picker on Enter", async () => {
const result = await runJourney([
step("What should REA set up?", "\r"),
step("Which agents should use REA?", "\u0003"),
]);
expect(result.output).toContain("Codex (detected)");
expect(result.output).toContain("Setup cancelled. No changes were made.");
expect(result.decision.approved).toBe(false);
});
it("offers one bundled repair when MCP is aligned but the skill is missing", async () => {
it("shows detected and absent clients without preselecting detected clients", async () => {
const result = await runJourney(
[step("What should REA set up?", "\r"), step("Apply this change?", "\r")],
[step("Which agents should use REA?", "\u001b[B\r")],
false,
actions.filter(({ kind }) => kind !== "configure_client"),
[actions[0]],
);
expect(result.output).toContain("No agent integrations need configuration");
expect(result.output).toContain("Detected: Codex");
expect(result.output).toContain(
"Agent integration (MCP + guided workflow)",
"Not detected · configuration is still available",
);
expect(result.output).not.toContain(
"REA reverse-engineering skill (skill)",
);
expect(result.output).toContain("INSTALL REA reverse-engineering skill");
expect(result.output).not.toContain("CREATE Codex");
expect(result.output).not.toContain(
"INSTALL Hopper deep-analysis provider",
);
expect(result.decision).toEqual({
approved: true,
selectedActionIds: ["install_skill"],
});
expect(result.output).toContain("Which agents should use REA?");
expect(result.output).not.toContain("What should REA set up?");
expect(result.decision.selectedActionIds).toEqual([]);
});
it("pre-selects all detected agents in the agent picker", async () => {
it("selects an absent OpenCode client and bundles its skill", async () => {
const result = await runJourney(
[
step("What should REA set up?", "\r"),
step("Which agents should use REA?", "\u0003"),
step("Which agents should use REA?", "\u001b[B \r"),
step("Apply these 2 changes?", "\r"),
],
false,
[
actions[0],
{
...actions[0],
id: "configure_client:cursor",
label: "Cursor",
target: "/isolated/.cursor/mcp.json",
id: "configure_client:opencode",
label: "OpenCode",
target: "/isolated/.config/opencode/opencode.json",
},
...actions.slice(1),
actions[1],
],
);
expect(result.output).toContain("Codex (detected)");
expect(result.output).toContain("Cursor (detected)");
expect(result.decision.approved).toBe(false);
});
});
describe("interactive setup selection and confirmation", () => {
it("retains the bundled skill even when all agents are deselected (#399)", async () => {
const result = await runJourney([
step("What should REA set up?", "\r"),
step("Which agents should use REA?", " \r"),
step("Apply this change?", "\r"),
expect(result.output).toContain("CREATE OpenCode");
expect(result.decision.selectedActionIds).toEqual([
"configure_client:opencode",
"install_skill",
]);
expect(result.output).toContain("Ready to review");
expect(result.output).toContain("INSTALL REA reverse-engineering skill");
expect(result.output).not.toContain("CREATE Codex");
expect(result.decision).toEqual({
approved: true,
selectedActionIds: ["install_skill"],
});
expect(result.decision.approved).toBe(true);
});
it("defaults the final confirmation to Yes, apply", async () => {
const result = await runJourney([
step("What should REA set up?", "\r"),
step("Which agents should use REA?", "\r"),
step("Apply these 2 changes?", "\r"),
]);
expect(result.output).toContain("Ready to review");
expect(result.output).toContain("CREATE Codex");
expect(result.output).toContain("/isolated/.codex/config.toml");
expect(result.output).toContain("INSTALL REA reverse-engineering skill");
expect(result.output).not.toContain(
"INSTALL Hopper deep-analysis provider",
);
expect(result.output).toContain("Yes, apply");
expect(result.decision).toEqual({
approved: true,
selectedActionIds: ["configure_client:codex", "install_skill"],
});
});
it("can still be cancelled at the final confirmation", async () => {
const result = await runJourney([
step("What should REA set up?", "\r"),
step("Which agents should use REA?", "\r"),
step("Apply these 2 changes?", "\u001b[D\r"),
]);
expect(result.output).toContain("Ready to review");
expect(result.output).toContain("Setup cancelled. No changes were made.");
expect(result.decision).toEqual({
approved: false,
selectedActionIds: ["configure_client:codex", "install_skill"],
});
});
it("defaults accessible agent integration to Yes and others to No", async () => {
it("shows the launcher, backup, and path before final approval", async () => {
const result = await runJourney(
[
step("Set up Agent integration (MCP + guided workflow)?", "\r"),
step("Set up Hopper deep-analysis provider (provider)?", "\r"),
step("Which agents should use REA?", " \r"),
step("Apply these 2 changes?", "\r"),
],
false,
[
{
...actions[0],
operation: "update",
backupPath: "/isolated/.codex/config.toml.bak",
commands: ["npx -y rea-agents@3.2.1 mcp"],
},
actions[1],
],
);
expect(result.output).toContain("/isolated/.codex/config.toml.bak");
expect(result.output).toContain("command: npx -y rea-agents@3.2.1 mcp");
expect(result.output.indexOf("command:")).toBeLessThan(
result.output.indexOf("Apply these 2 changes?"),
);
});
it("treats final No as cancellation", async () => {
const result = await runJourney([
step("Which agents should use REA?", " \r"),
step("Apply these 2 changes?", "\u001b[D\r"),
]);
expect(result.output).toContain("Setup cancelled. No changes were made.");
expect(result.decision.cancelled).toBe(true);
expect(result.decision.approved).toBe(false);
});
it("restores the terminal after Ctrl-C during selection", async () => {
const result = await runJourney([
step("Which agents should use REA?", "\u0003"),
]);
expect(result.output).toContain("\u001b[?25h");
expect(result.decision.cancelled).toBe(true);
});
it("can install the skill for CLI use without an agent registration", async () => {
const result = await runJourney([
step("Which agents should use REA?", "\r"),
step("Install the guided REA skill for CLI use?", "\u001b[D\r"),
step("Apply this change?", "\r"),
]);
expect(result.decision.selectedActionIds).toEqual(["install_skill"]);
expect(result.decision.approved).toBe(true);
});
it("offers Hopper separately and defaults against installing it", async () => {
const result = await runJourney(
[
step("Which agents should use REA?", " \r"),
step("Install Hopper for deep binary analysis?", "\r"),
step("Apply these 2 changes?", "\r"),
],
false,
actions,
);
expect(result.decision.selectedActionIds).toEqual([
"configure_client:codex",
"install_skill",
]);
});
it("uses sequential prompts without auto-selecting detected agents in accessible mode", async () => {
const result = await runJourney(
[
step("Configure Codex?", "\r"),
step("Configure OpenCode?", "\u001b[A\r"),
step("Apply this change?", "\r"),
],
true,
actions.filter(({ kind }) => kind !== "configure_client"),
[{ ...actions[0], id: "configure_client:opencode", label: "OpenCode" }],
);
expect(result.output).toContain("Ready to review");
expect(result.output).toContain("INSTALL REA reverse-engineering skill");
expect(result.decision).toEqual({
approved: true,
selectedActionIds: ["install_skill"],
});
expect(result.decision.selectedActionIds).toEqual([
"configure_client:opencode",
]);
});
it("allows accessible opt-out of the pre-selected agent integration", async () => {
it("preselects only a prior REA registration", async () => {
const result = await runJourney(
[
step("Set up Agent integration (MCP + guided workflow)?", "\u001b[B\r"),
step("Set up Hopper deep-analysis provider (provider)?", "\r"),
step("Which agents should use REA?", "\r"),
step("Apply these 2 changes?", "\r"),
],
true,
false,
agentActions,
["codex"],
);
expect(result.output).toContain("Nothing selected. No changes were made.");
expect(result.decision.selectedActionIds).toEqual([]);
expect(result.decision.selectedActionIds).toEqual([
"configure_client:codex",
"install_skill",
]);
});
});
describe("interactive setup completion", () => {
it("frames completion around the capabilities that are now ready", async () => {
const { stderr } = await execute(
process.execPath,
[
"--input-type=module",
"--eval",
it.each([
{ npmCommand: "", launcher: "rea" },
{ npmCommand: "exec", launcher: "npx rea-agents" },
])(
"prints an available next command for $launcher invocation",
async ({ npmCommand, launcher }) => {
const { stderr } = await execute(
process.execPath,
[
'import { renderInteractiveSetupResult } from "./dist/cliSetup.js";',
"renderInteractiveSetupResult({",
' status: "ready",',
" plannedActions: [],",
" appliedActions: [],",
' clients: { codex: { status: "configured" } },',
" doctor: {",
" healthy: true,",
' hopperPath: "/Applications/Hopper",',
" checks: [],",
' providerInspections: [{ id: "ghidra", available: true }],',
' identity: { skill: { state: "aligned" }, registrations: [{ client: "codex", state: "aligned" }] },',
" },",
"});",
].join("\n"),
],
{
cwd: process.cwd(),
env: { ...process.env, NO_COLOR: "1" },
},
);
"--input-type=module",
"--eval",
[
'import { renderInteractiveSetupResult } from "./dist/cliSetup.js";',
"renderInteractiveSetupResult({",
' status: "ready",',
" plannedActions: [],",
" appliedActions: [],",
' clients: { codex: { status: "configured" } },',
" doctor: {",
" healthy: true,",
' availableProviders: ["hopper", "ghidra"],',
' hopperPath: "/Applications/Hopper",',
" checks: [],",
' providerInspections: [{ id: "ghidra", available: true }],',
' identity: { skill: { state: "aligned" }, registrations: [{ client: "codex", state: "aligned" }] },',
" },",
"});",
].join("\n"),
],
{
cwd: process.cwd(),
env: { ...process.env, npm_command: npmCommand, NO_COLOR: "1" },
},
);
expect(stderr).toContain("What you can do now");
expect(stderr).toContain("Deep analysis: Hopper and Ghidra");
expect(stderr).toContain("Agent access: Codex");
expect(stderr).toContain("Guided reverse-engineering workflows: installed");
expect(stderr).toContain("CLI: rea analyze /path/to/app");
expect(stderr).toContain(
'Try in Codex: "Explain how a feature works in /path/to/app and show the evidence."',
);
});
expect(stderr).toContain("What you can do now");
expect(stderr).toContain("Deep analysis: Hopper and Ghidra");
expect(stderr).toContain("Agent access: Codex");
expect(stderr).toContain(
"Guided reverse-engineering workflows: installed",
);
expect(stderr).toContain(`CLI: ${launcher} analyze /path/to/app`);
expect(stderr).toContain(
'Try in Codex: "Explain how a feature works in /path/to/app and show the evidence."',
);
},
);
});
interface JourneyStep {
@@ -277,10 +271,7 @@ interface JourneyStep {
interface JourneyResult {
readonly output: string;
readonly decision: {
readonly approved: boolean;
readonly selectedActionIds: readonly string[];
};
readonly decision: z.infer<typeof decisionSchema>;
}
const step = (prompt: string, input: string): JourneyStep => ({
@@ -291,13 +282,19 @@ const step = (prompt: string, input: string): JourneyStep => ({
const runJourney = async (
steps: readonly JourneyStep[],
accessible = false,
journeyActions: readonly object[] = actions,
journeyActions: readonly object[] = agentActions,
initialClientIds: readonly string[] = [],
): Promise<JourneyResult> => {
const isolatedHome = await createTestTempDirectory("rea-cli-setup-test-");
const script = [
'import { confirmInteractiveSetup } from "./dist/cliSetup.js";',
`const actions = ${JSON.stringify(journeyActions)};`,
`const decision = await confirmInteractiveSetup(actions, ${JSON.stringify(accessible)});`,
`const context = ${JSON.stringify({ stage: "select", clientStates, selectedClientIds: initialClientIds, clientSelectionAllowed: true })};`,
`let decision = await confirmInteractiveSetup(actions, ${JSON.stringify(accessible)}, context);`,
"if (!decision.cancelled && decision.selectedActionIds.length > 0) {",
" const selected = new Set(decision.selectedActionIds);",
` decision = await confirmInteractiveSetup(actions.filter(({ id }) => selected.has(id)), ${JSON.stringify(accessible)}, { ...context, stage: "confirm", clientSelectionAllowed: false });`,
"}",
`process.stdout.write(${JSON.stringify(`\n${decisionMarker}`)} + JSON.stringify(decision) + "\\n");`,
].join("\n");
@@ -362,7 +359,7 @@ const runJourney = async (
try {
finish(undefined, {
output,
decision: JSON.parse(serialized) as JourneyResult["decision"],
decision: decisionSchema.parse(JSON.parse(serialized)),
});
} catch (cause: unknown) {
finish(cause instanceof Error ? cause : new Error(String(cause)));
@@ -0,0 +1,273 @@
import { mkdir, readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { parse as parseJsonc, type ParseError } from "jsonc-parser";
import { readClientRegistrationStatuses } from "../../../src/application/ClientRegistrationStatus.js";
import { configureClientConfiguration } from "../../../src/application/SetupClientConfiguration.js";
import { systemUninstallHost } from "../../../src/application/Uninstall.js";
import { supportedClients } from "../../../src/application/SupportedClients.js";
import { PRODUCT_IDENTITY } from "../../../src/identity.js";
import { isOwnedClientRegistrationCommand } from "../../../src/application/ClientRegistrationIdentity.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
const command = [
"npx",
"-y",
PRODUCT_IDENTITY.registrationPackageSpecifier,
"mcp",
] as const;
const getClients = (home: string) =>
supportedClients(home).filter(({ name }) =>
["opencode", "antigravity", "copilot_cli", "vscode", "devin"].includes(
name,
),
);
describe("additional client configuration dialects", () => {
it.each([
"opencode",
"antigravity",
"copilot_cli",
"vscode",
"devin",
] as const)("registers, reads back, and uninstalls %s", async (name) => {
const home = await createTestTempDirectory("rea-client-dialect-");
const client = getClients(home).find(
(candidate) => candidate.name === name,
);
expect(client).toBeDefined();
if (client === undefined) throw new Error(`missing ${name} client`);
await mkdir(client.markerPath ?? home, { recursive: true });
const configured = await configureClientConfiguration(client, {}, command);
expect(configured.status).toBe("configured");
expect(await configureClientConfiguration(client, {}, command)).toEqual({
status: "unchanged",
});
const text = await readFile(client.configPath, "utf8");
const document = parseJsonc(text) as Record<string, unknown>;
const serversKey =
name === "opencode"
? "mcp"
: name === "vscode"
? "servers"
: "mcpServers";
const servers = document[serversKey] as Record<
string,
Record<string, unknown>
>;
const registration = servers[PRODUCT_IDENTITY.mcpServerKey];
expect(registration).toBeDefined();
if (name === "opencode")
expect(registration).toMatchObject({
type: "local",
command,
enabled: true,
});
if (name === "vscode")
expect(registration).toMatchObject({
type: "stdio",
command: "npx",
args: command.slice(1),
});
if (name === "copilot_cli")
expect(registration).toMatchObject({ type: "stdio", tools: ["*"] });
const statuses = await readClientRegistrationStatuses(home);
expect(statuses).toEqual(
expect.arrayContaining([
expect.objectContaining({ client: name, state: "aligned", command }),
]),
);
const removed = await systemUninstallHost(home).removeClient(client);
expect(removed.status).toBe("removed");
const afterRemoval = parseJsonc(
await readFile(client.configPath, "utf8"),
) as Record<string, unknown>;
expect(
(afterRemoval[serversKey] as Record<string, unknown>)[
PRODUCT_IDENTITY.mcpServerKey
],
).toBeUndefined();
});
it("preserves OpenCode JSONC comments and sibling registrations during update and removal", async () => {
const home = await createTestTempDirectory("rea-opencode-jsonc-");
const client = getClients(home).find(({ name }) => name === "opencode");
expect(client).toBeDefined();
if (client === undefined) throw new Error("missing OpenCode client");
await mkdir(client.markerPath ?? home, { recursive: true });
const original = `{
// Client-wide preferences stay intact.
"model": "provider/model",
"mcp": {
// An independently managed server.
"other": { "type": "local", "command": ["node", "other.js"] },
},
}\n`;
await writeFile(client.configPath, original);
expect(
await configureClientConfiguration(client, {}, command),
).toMatchObject({
status: "configured",
backupPath: `${client.configPath}.rea.backup`,
});
const updated = await readFile(client.configPath, "utf8");
const errors: ParseError[] = [];
const parsed = parseJsonc(updated, errors, {
allowTrailingComma: true,
}) as Record<string, unknown>;
expect(errors).toEqual([]);
expect(updated).toContain("// Client-wide preferences stay intact.");
expect(updated).toContain("// An independently managed server.");
expect(parsed.model).toBe("provider/model");
expect((parsed.mcp as Record<string, unknown>).other).toBeDefined();
expect(await readFile(`${client.configPath}.rea.backup`, "utf8")).toBe(
original,
);
expect((await systemUninstallHost(home).removeClient(client)).status).toBe(
"removed",
);
const removedText = await readFile(client.configPath, "utf8");
const removedErrors: ParseError[] = [];
const removed = parseJsonc(removedText, removedErrors, {
allowTrailingComma: true,
}) as Record<string, unknown>;
expect(removedErrors).toEqual([]);
expect(removedText).toContain("// Client-wide preferences stay intact.");
expect(removedText).toContain("// An independently managed server.");
expect((removed.mcp as Record<string, unknown>).rea).toBeUndefined();
expect((removed.mcp as Record<string, unknown>).other).toBeDefined();
});
it("rejects malformed OpenCode JSONC without creating a backup or changing bytes", async () => {
const home = await createTestTempDirectory("rea-opencode-invalid-");
const client = getClients(home).find(({ name }) => name === "opencode");
expect(client).toBeDefined();
if (client === undefined) throw new Error("missing OpenCode client");
await mkdir(client.markerPath ?? home, { recursive: true });
const invalid = '{ "mcp": { /* broken */ "rea": [ }';
await writeFile(client.configPath, invalid);
expect(await configureClientConfiguration(client, {}, command)).toEqual({
status: "failed",
reason: "readback",
});
expect(await readFile(client.configPath, "utf8")).toBe(invalid);
});
});
describe("platform-aware client config paths", () => {
it.each([
[
"darwin",
"/home/a",
{},
"/home/a/Library/Application Support/Code/User/mcp.json",
],
["linux", "/home/a", {}, "/home/a/.config/Code/User/mcp.json"],
[
"win32",
"C:/Users/a",
{},
"C:/Users/a/AppData/Roaming/Code/User/mcp.json",
],
[
"linux",
"/home/a",
{ XDG_CONFIG_HOME: "/config" },
"/config/Code/User/mcp.json",
],
] as const)(
"resolves VS Code user MCP path for %s",
(platform, home, env, expected) => {
expect(
supportedClients(home, platform, env).find(
({ name }) => name === "vscode",
)?.configPath,
).toBe(expected);
},
);
it("honors Copilot CLI and Devin platform configuration roots", () => {
expect(
supportedClients("/home/a", "linux", {
COPILOT_HOME: "/custom/copilot",
XDG_CONFIG_HOME: "/custom/config",
}).find(({ name }) => name === "copilot_cli")?.configPath,
).toBe("/custom/copilot/mcp-config.json");
expect(
supportedClients("C:/Users/a", "win32", {
APPDATA: "D:/Profile/Roaming",
}).find(({ name }) => name === "devin")?.configPath,
).toBe("D:/Profile/Roaming/devin/mcp_config.json");
});
it("prefers an existing OpenCode JSONC file and honors explicit harness roots", async () => {
const home = await createTestTempDirectory("rea-config-overrides-");
const opencodeDirectory = join(home, ".config/opencode");
await mkdir(opencodeDirectory, { recursive: true });
await writeFile(join(opencodeDirectory, "opencode.jsonc"), "{}\n");
const clients = supportedClients(home, "linux", {});
expect(clients.find(({ name }) => name === "opencode")?.configPath).toBe(
join(opencodeDirectory, "opencode.jsonc"),
);
expect(
supportedClients(home, "linux", {
OPENCODE_CONFIG: "/custom/open-code.jsonc",
CLAUDE_CONFIG_DIR: "/custom/claude",
CODEX_HOME: "/custom/codex",
}).filter(({ name }) =>
["opencode", "claude_code", "codex"].includes(name),
),
).toEqual(
expect.arrayContaining([
expect.objectContaining({
name: "opencode",
configPath: "/custom/open-code.jsonc",
}),
expect.objectContaining({
name: "claude_code",
configPath: "/custom/claude/.claude.json",
}),
expect.objectContaining({
name: "codex",
configPath: "/custom/codex/config.toml",
}),
]),
);
});
it("recognizes prior exact REA releases while rejecting foreign package commands", () => {
expect(
isOwnedClientRegistrationCommand([
"npx",
"-y",
`${PRODUCT_IDENTITY.packageName}@3.2.0`,
"mcp",
]),
).toBe(true);
expect(
isOwnedClientRegistrationCommand(["npx", "-y", "another-package", "mcp"]),
).toBe(false);
expect(
isOwnedClientRegistrationCommand(
[process.execPath, "/packaged/rea.mjs", "mcp"],
"/packaged/rea.mjs",
),
).toBe(true);
expect(
isOwnedClientRegistrationCommand(
["node", "/packaged/other-agent.mjs", "mcp"],
"/packaged/rea.mjs",
),
).toBe(false);
});
});
@@ -41,7 +41,11 @@ describe("client configuration filesystem lifecycle", () => {
".cursor",
".gemini",
".codeium/windsurf",
".devin",
".config/devin",
".config/opencode",
".gemini/config",
".copilot",
"Library/Application Support/Code/User",
])
await mkdir(join(home, marker), { recursive: true });
const detected = await detectClients(home);
@@ -53,13 +57,15 @@ describe("client configuration filesystem lifecycle", () => {
"gemini_cli",
"windsurf",
"devin",
"opencode",
"antigravity",
"copilot_cli",
"vscode",
]);
expect(
detected.find(({ name }) => name === "claude_code")?.configPath,
).toBe(join(home, ".claude.json"));
expect(detected.find(({ name }) => name === "devin")?.format).toBe(
"unsupported",
);
expect(detected.find(({ name }) => name === "devin")?.format).toBe("json");
const emptyHome = await createTestTempDirectory("rea-empty-");
roots.push(emptyHome);
expect(await detectClients(emptyHome)).toEqual([]);
@@ -9,6 +9,32 @@ import { readClientRegistrationStatuses } from "../../../src/application/ClientR
import { PRODUCT_IDENTITY } from "../../../src/identity.js";
describe("client registration status", () => {
it("discovers Claude Code from its config file without a marker directory", async () => {
const home = await createTestTempDirectory("rea-claude-config-only-");
await writeFile(
join(home, ".claude.json"),
JSON.stringify({
mcpServers: {
rea: {
command: "npx",
args: ["-y", PRODUCT_IDENTITY.registrationPackageSpecifier, "mcp"],
},
},
}),
);
const statuses = await readClientRegistrationStatuses(home, "/current/rea");
expect(statuses).toEqual([
expect.objectContaining({
client: "claude_code",
config_path: join(home, ".claude.json"),
state: "aligned",
remediation: null,
}),
]);
});
it("distinguishes aligned, stale, missing, and invalid registrations", async () => {
const home = await createTestTempDirectory("rea-registrations-");
await Promise.all([
+18
View File
@@ -10,6 +10,24 @@ afterEach(() => {
});
describe("CLI operation status", () => {
it("treats a requested setup dry run and cancellation as successful outcomes", async () => {
for (const status of ["planned", "cancelled"]) {
process.exitCode = undefined;
await logCliCommand(silentLogger, "setup", () =>
Promise.resolve({ status }),
);
expect(process.exitCode).toBeUndefined();
}
});
it("keeps unapproved setup applications unsuccessful", async () => {
process.exitCode = undefined;
await logCliCommand(silentLogger, "setup", () =>
Promise.resolve({ status: "needs_confirmation" }),
);
expect(process.exitCode).toBe(1);
});
it("sets a nonzero process status without replacing structured output", async () => {
const output = {
error: "Analysis failed",
@@ -0,0 +1,286 @@
import { mkdir, readFile, rm, writeFile, access } from "node:fs/promises";
import { dirname, join, resolve } from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { err, ok } from "../../src/domain/result.js";
import { PRODUCT_IDENTITY } from "../../src/identity.js";
import { supportedClients } from "../../src/application/SupportedClients.js";
import {
existingMaintenanceScope,
planIntegrationMaintenance,
} from "../../src/application/UpdateMaintenance.js";
import {
runUpdateCommand,
systemUpdateHost,
} from "../../src/application/UpdateRuntime.js";
import { createTestTempDirectory } from "../fixtures/temporaryDirectory.js";
const entryPoint = resolve("scripts/rea.mjs");
let home: string;
beforeEach(async () => {
home = await createTestTempDirectory("rea-update-maintenance-");
for (const [name, value] of Object.entries({
HOME: home,
USERPROFILE: home,
APPDATA: join(home, "AppData", "Roaming"),
CLAUDE_CONFIG_DIR: home,
CODEX_HOME: join(home, ".codex"),
COPILOT_HOME: join(home, ".copilot"),
XDG_CONFIG_HOME: join(home, ".config"),
OPENCODE_CONFIG: join(home, ".config", "opencode", "opencode.jsonc"),
}))
vi.stubEnv(name, value);
});
afterEach(async () => {
vi.unstubAllEnvs();
await rm(home, { recursive: true, force: true });
});
const writeClient = async (id: string, content: string): Promise<string> => {
const client = supportedClients(home).find(({ name }) => name === id);
if (client === undefined) throw new Error(`Unknown test client ${id}`);
await mkdir(dirname(client.configPath), { recursive: true });
await writeFile(client.configPath, content);
return client.configPath;
};
const writeSkill = async (content: string): Promise<string> => {
const path = join(
home,
".agents",
"skills",
PRODUCT_IDENTITY.skillName,
"SKILL.md",
);
await mkdir(dirname(path), { recursive: true });
await writeFile(path, content);
return path;
};
const staleCodex =
'[mcp_servers.rea]\ncommand = "npx"\nargs = ["-y", "rea-agents@0.1.0", "mcp"]\n';
const action = {
id: "configure_client:codex",
kind: "configure_client",
label: "Codex",
target: "/test/.codex/config.toml",
detail: "Refresh the pinned REA version",
external: false,
operation: "update",
backupPath: "/test/.codex/config.toml.rea.backup",
commands: ["rea mcp"],
};
describe("existing REA integration maintenance", () => {
it("selects owned registrations while preserving unconfigured, foreign, and disabled choices", async () => {
await writeClient("codex", staleCodex);
await writeClient("claude_code", '{"mcpServers":{}}');
await writeClient(
"cursor",
'{"mcpServers":{"rea":{"command":"foreign-server","args":[]}}}',
);
await writeClient(
"opencode",
'{"mcp":{"rea":{"type":"local","command":["npx","-y","rea-agents@0.1.0","mcp"],"enabled":false}}}',
);
await writeClient(
"vscode",
JSON.stringify({
servers: { rea: { type: "stdio", command: entryPoint, args: ["mcp"] } },
}),
);
await expect(existingMaintenanceScope(home, entryPoint)).resolves.toEqual({
clients: ["codex", "vscode"],
skill: false,
});
});
it("does not install a missing skill or overwrite an unrelated skill", async () => {
await expect(existingMaintenanceScope(home, entryPoint)).resolves.toEqual({
clients: [],
skill: false,
});
await writeSkill("---\nname: another-skill\n---\nUser-authored content\n");
await expect(existingMaintenanceScope(home, entryPoint)).resolves.toEqual({
clients: [],
skill: false,
});
});
it("includes an existing REA skill and leaves files untouched", async () => {
const path = await writeSkill(
`---\nname: ${PRODUCT_IDENTITY.skillName}\nmetadata:\n version: "1"\n---\n# REA\n`,
);
const original = await readFile(path, "utf8");
await expect(existingMaintenanceScope(home, entryPoint)).resolves.toEqual({
clients: [],
skill: true,
});
expect(await readFile(path, "utf8")).toBe(original);
});
it("skips setup entirely when there is no existing integration", async () => {
let invoked = false;
const result = await planIntegrationMaintenance(
home,
entryPoint,
async () => {
invoked = true;
return err("Unexpected setup");
},
);
expect(result).toEqual({ status: "current", plannedActions: [] });
expect(invoked).toBe(false);
});
it("returns exact backup and command evidence with a scoped unapplied setup command", async () => {
await writeClient("codex", staleCodex);
const recorded: string[][] = [];
const result = await planIntegrationMaintenance(
home,
entryPoint,
async (command) => {
recorded.push([...command]);
return ok(
JSON.stringify({ status: "planned", plannedActions: [action] }),
);
},
);
expect(recorded).toEqual([
[
process.execPath,
entryPoint,
"setup",
"--client",
"codex",
"--skill=false",
"--dry-run",
"--json",
],
]);
expect(result).toEqual({
status: "planned",
scope: { clients: ["codex"], skill: false },
command: recorded[0]?.slice(0, -2),
plannedActions: [action],
});
});
it.each([
"{broken",
JSON.stringify({ status: "ready", plannedActions: [action] }),
JSON.stringify({
status: "planned",
plannedActions: [{ ...action, kind: "install_hopper", external: true }],
}),
JSON.stringify({
status: "planned",
plannedActions: [{ ...action, id: "configure_client:cursor" }],
}),
])("rejects malformed or out-of-scope subprocess plans", async (output) => {
await writeClient("codex", staleCodex);
expect(
await planIntegrationMaintenance(home, entryPoint, async () =>
ok(output),
),
).toMatchObject({ status: "unavailable" });
});
it("preserves actual setup failure diagnostics", async () => {
await writeClient("codex", staleCodex);
expect(
await planIntegrationMaintenance(home, entryPoint, async () =>
err("EACCES /test/.codex/config.toml"),
),
).toEqual({
status: "unavailable",
remediation: "EACCES /test/.codex/config.toml",
});
});
it("runs real setup as a noninteractive dry run and creates no new integrations or backups", async () => {
const configPath = await writeClient("codex", staleCodex);
const untouched = await writeClient("claude_code", '{"mcpServers":{}}');
vi.stubEnv("npm_command", "exec");
const result = await planIntegrationMaintenance(
home,
entryPoint,
runUpdateCommand,
);
expect(result).toMatchObject({
status: "planned",
scope: { clients: ["codex"], skill: false },
plannedActions: [
{ id: "configure_client:codex", kind: "configure_client" },
],
});
expect(await readFile(configPath, "utf8")).toBe(staleCodex);
expect(await readFile(untouched, "utf8")).toBe('{"mcpServers":{}}');
await expect(access(`${configPath}.rea.backup`)).rejects.toMatchObject({
code: "ENOENT",
});
await expect(
access(join(home, ".agents", "skills", PRODUCT_IDENTITY.skillName)),
).rejects.toMatchObject({ code: "ENOENT" });
});
});
describe("update subprocess boundaries", () => {
it("exposes update as the sole CLI command", async () => {
const help = await runUpdateCommand([
process.execPath,
entryPoint,
"--help",
]);
expect(help.ok).toBe(true);
if (help.ok) {
expect(help.value).toMatch(/^\s{2}update\s/mu);
expect(help.value).not.toMatch(/^\s{2}upgrade\s/mu);
}
const removed = await runUpdateCommand([
process.execPath,
entryPoint,
"upgrade",
"--json",
]);
expect(removed.ok).toBe(false);
});
it("captures output through stream closure and keeps arguments literal", async () => {
const literal = 'space and $(echo bad); & | "quotes"';
const result = await runUpdateCommand([
process.execPath,
"-e",
'process.stdout.write("x".repeat(1024 * 1024) + process.argv[1])',
literal,
]);
expect(result).toEqual(ok(`${"x".repeat(1024 * 1024)}${literal}`));
});
it("reports actual stderr and launch failures", async () => {
await expect(
runUpdateCommand([
process.execPath,
"-e",
'process.stderr.write("EACCES /test/install"); process.exitCode = 2',
]),
).resolves.toEqual(err("EACCES /test/install"));
const missing = await runUpdateCommand([join(home, "missing-executable")]);
expect(missing).toMatchObject({ ok: false });
if (!missing.ok) expect(missing.error).toContain("ENOENT");
});
it("verifies the requested package entry rather than PATH's rea", async () => {
const packageRoot = join(home, "package");
const script = join(packageRoot, "scripts", "rea.mjs");
await mkdir(dirname(script), { recursive: true });
await writeFile(script, 'process.stdout.write("3.3.0\\n")');
await expect(
systemUpdateHost(packageRoot, home).installedVersion({
prefix: home,
packageRoot,
}),
).resolves.toEqual(ok("3.3.0"));
});
});