mirror of
https://github.com/morluto/rea.git
synced 2026-11-29 09:56:23 +00:00
* fix(cli): reject invalid inline values and honor requested output on terminals - Reject inline boolean and empty number values the schema cannot accept instead of coercing --skill=yes to false or --limit= to 0. - Give captured mcp add output the terminal presentation of every other command through one shared result destination. - Show the unapproved setup plan whose remediation asks a terminal reader to review it, and open the setup rail once when a scoped run starts at approval. - Treat --full-output and --token-count as requesting the result document, so setup and argument errors no longer add terminal presentation beside it. - Answer --schema for an unknown command in the selected format, and set the exit code instead of exiting so piped stdout drains. * fix(cli): keep rejected boolean and number literals across repeated flags Binding stored one scalar value, so a later valid flag replaced an earlier literal before the schema could reject it. Boolean and number literals the field rejects now stay bound, including decimal unions and count options, while repeated valid flags still use the last value. --dry-run keeps its own error. * test(cli): assert the terminal full-output failure envelope The terminal --full-output regression only checked that usage text was absent. Decode the default document and the --json envelope and require VALIDATION_ERROR with the skill field's invalid_type error. * test(cli): accept a counted setup approval prompt A scoped terminal plan names every eligible action, so a Linux host that can install Hopper asks "Apply these N changes?" rather than the singular question. The consent helper now answers either prompt, and the rail test finds that question before checking the intro was rendered once. --------- Co-authored-by: Cursor Agent <cursoragent@cursor.com>
1058 lines
34 KiB
TypeScript
1058 lines
34 KiB
TypeScript
import { createVerifierCommands } from "../../../scripts/lib/verify-commands.mjs";
|
|
import { withVerifierCleanup } from "../../../scripts/lib/verifier-cleanup.mjs";
|
|
import {
|
|
access,
|
|
lstat,
|
|
mkdir,
|
|
readFile,
|
|
readdir,
|
|
rm,
|
|
symlink,
|
|
writeFile,
|
|
} from "node:fs/promises";
|
|
import { dirname, join, resolve } from "node:path";
|
|
import { spawn } from "@lydell/node-pty";
|
|
import { describe, expect, it, onTestFinished } from "vitest";
|
|
import { z } from "zod";
|
|
import { parse as parseToml } from "smol-toml";
|
|
|
|
import { manualRegistrationRemediation } from "../../../src/application/SupportedClients.js";
|
|
import type {
|
|
SetupClientState,
|
|
SetupResult,
|
|
} from "../../../src/application/SetupTypes.js";
|
|
import { supportedClientRegistrationProfile } from "../../fixtures/clientRegistrationProfile.js";
|
|
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
|
import { cliTest, type TestCli } from "../../support/cli/cliFixture.js";
|
|
|
|
const execute = async (
|
|
command: string,
|
|
arguments_: readonly string[],
|
|
options: { readonly cwd: string; readonly env: NodeJS.ProcessEnv },
|
|
) => {
|
|
const commands = await createVerifierCommands();
|
|
onTestFinished(() => commands.close());
|
|
return withVerifierCleanup(
|
|
() => commands.exec(command, arguments_, { ...options, timeout: 15_000 }),
|
|
[() => commands.close()],
|
|
);
|
|
};
|
|
const decisionMarker = "REA_SETUP_DECISION:";
|
|
const isolatedSetupEnvironment = (home: string) => ({
|
|
HOME: home,
|
|
USERPROFILE: home,
|
|
CODEX_HOME: join(home, ".codex"),
|
|
XDG_CONFIG_HOME: join(home, ".config"),
|
|
XDG_DATA_HOME: join(home, ".local", "share"),
|
|
XDG_CACHE_HOME: join(home, ".cache"),
|
|
});
|
|
const runSetup = (cli: TestCli, home: string, dryRun: string) =>
|
|
cli.run({
|
|
arguments: [
|
|
"setup",
|
|
"--yes",
|
|
"--client",
|
|
"codex",
|
|
"--skill=false",
|
|
dryRun,
|
|
"--format",
|
|
"json",
|
|
],
|
|
cwd: home,
|
|
environment: isolatedSetupEnvironment(home),
|
|
});
|
|
const decisionSchema = z.object({
|
|
approved: z.boolean(),
|
|
selectedActionIds: z.array(z.string()),
|
|
cancelled: z.boolean().optional(),
|
|
});
|
|
|
|
const actions = [
|
|
{
|
|
id: "configure_client:codex",
|
|
kind: "configure_client",
|
|
label: "Codex",
|
|
target: "/isolated/.codex/config.toml",
|
|
detail: "Add the REA MCP registration for Codex.",
|
|
external: false,
|
|
operation: "create",
|
|
},
|
|
{
|
|
id: "install_skill",
|
|
kind: "install_skill",
|
|
label: "REA reverse-engineering skill",
|
|
target: "/isolated/.agents/skills/reverse-engineering/SKILL.md",
|
|
detail: "Install the bundled reverse-engineering skill.",
|
|
external: false,
|
|
operation: "install",
|
|
},
|
|
{
|
|
id: "install_hopper",
|
|
kind: "install_hopper",
|
|
label: "Hopper deep-analysis provider",
|
|
target: "/isolated/Applications/Hopper Disassembler.app",
|
|
detail: "Install the verified Hopper package.",
|
|
external: true,
|
|
operation: "install",
|
|
},
|
|
] as const;
|
|
|
|
const clientStates = [
|
|
{
|
|
client: {
|
|
name: "codex",
|
|
registrationProfile: supportedClientRegistrationProfile("codex"),
|
|
format: "toml",
|
|
configPath: join(".codex", "config.toml"),
|
|
markerPath: ".codex",
|
|
},
|
|
detected: true,
|
|
configured: false,
|
|
status: "needs_configuration",
|
|
},
|
|
{
|
|
client: {
|
|
name: "opencode",
|
|
registrationProfile: supportedClientRegistrationProfile("opencode"),
|
|
format: "opencode",
|
|
configPath: join(".config", "opencode", "opencode.json"),
|
|
markerPath: join(".config", "opencode"),
|
|
},
|
|
detected: false,
|
|
configured: false,
|
|
status: "missing",
|
|
},
|
|
] as const satisfies readonly SetupClientState[];
|
|
|
|
const agentActions = actions.filter(({ kind }) => kind !== "install_hopper");
|
|
|
|
cliTest.for(["--dry-run=abc", "--dry-run=", "--dry-run=ab\ncd"] as const)(
|
|
"rejects malformed setup dry-run value %s before approved changes are written",
|
|
async (dryRun, { cli }) => {
|
|
const home = await createTestTempDirectory("rea-cli-invalid-dry-run-");
|
|
const config = join(home, ".codex", "config.toml");
|
|
const result = await runSetup(cli, home, dryRun);
|
|
|
|
await expect(access(config)).rejects.toMatchObject({ code: "ENOENT" });
|
|
expect(result.exitCode).not.toBe(0);
|
|
expect(result.json).toMatchObject({
|
|
code: "PARSE_ERROR",
|
|
message: "Invalid --dry-run value; use true or false.",
|
|
});
|
|
expect(`${result.stdout}\n${result.stderr}`).not.toMatch(/^ +at /mu);
|
|
},
|
|
);
|
|
|
|
cliTest.for(["--dry-run=true", "--dry-run=false"] as const)(
|
|
"accepts explicit setup dry-run value %s",
|
|
async (dryRun, { cli }) => {
|
|
const home = await createTestTempDirectory("rea-cli-explicit-dry-run-");
|
|
const config = join(home, ".codex", "config.toml");
|
|
const result = await runSetup(cli, home, dryRun);
|
|
|
|
expect(result.exitCode, result.stderr).toBe(0);
|
|
if (dryRun === "--dry-run=true") {
|
|
expect(result.json).toMatchObject({ status: "planned" });
|
|
await expect(access(config)).rejects.toMatchObject({ code: "ENOENT" });
|
|
} else {
|
|
expect(result.json).toMatchObject({ status: "ready" });
|
|
await expect(access(config)).resolves.toBeUndefined();
|
|
}
|
|
},
|
|
);
|
|
|
|
cliTest(
|
|
"shows setup help even when a malformed dry-run value is present",
|
|
async ({ cli }) => {
|
|
const home = await createTestTempDirectory("rea-cli-help-invalid-dry-run-");
|
|
const config = join(home, ".codex", "config.toml");
|
|
const result = await cli.run({
|
|
arguments: ["setup", "--dry-run=abc", "--help"],
|
|
cwd: home,
|
|
environment: isolatedSetupEnvironment(home),
|
|
});
|
|
|
|
expect(result.exitCode).toBe(0);
|
|
expect(result.stdout).toContain("Usage: rea setup");
|
|
expect(result.stdout).not.toContain("Invalid --dry-run value");
|
|
await expect(access(config)).rejects.toMatchObject({ code: "ENOENT" });
|
|
},
|
|
);
|
|
|
|
cliTest(
|
|
"rejects an overridden malformed dry-run before changing existing Codex configuration",
|
|
async ({ cli }) => {
|
|
const selectedHome = await createTestTempDirectory(
|
|
"rea-cli-existing-dry-run-",
|
|
);
|
|
const config = join(selectedHome, ".codex", "config.toml");
|
|
const original = 'model = "retained-evidence"\n';
|
|
await mkdir(dirname(config), { recursive: true });
|
|
await writeFile(config, original);
|
|
const before = await lstat(config);
|
|
const result = await cli.run({
|
|
arguments: [
|
|
"setup",
|
|
"--yes",
|
|
"--client",
|
|
"codex",
|
|
"--skill=false",
|
|
"--dry-run=abc",
|
|
"--dry-run=false",
|
|
"--json",
|
|
],
|
|
cwd: selectedHome,
|
|
environment: isolatedSetupEnvironment(selectedHome),
|
|
});
|
|
expect(result.exitCode, result.stderr).toBe(1);
|
|
expect(result.json).toMatchObject({
|
|
code: "PARSE_ERROR",
|
|
message: "Invalid --dry-run value; use true or false.",
|
|
});
|
|
expect(await readFile(config, "utf8")).toBe(original);
|
|
expect((await lstat(config)).mtimeMs).toBe(before.mtimeMs);
|
|
expect(await readdir(dirname(config))).toEqual(["config.toml"]);
|
|
},
|
|
);
|
|
|
|
/**
|
|
* Approval asks about one change, or names the count when the host can also
|
|
* install Hopper. Either question is the consent prompt.
|
|
*/
|
|
const setupApprovalQuestion = /Apply this change\?|Apply these \d+ changes\?/u;
|
|
|
|
const runSetupInTty = async (
|
|
home: string,
|
|
arguments_: readonly string[],
|
|
approval?: boolean,
|
|
environment: NodeJS.ProcessEnv = {},
|
|
{ terminalStdin = true }: { readonly terminalStdin?: boolean } = {},
|
|
): Promise<{ readonly exitCode: number; readonly output: string }> => {
|
|
// Without a terminal stdin, only stdout and stderr stay on the terminal.
|
|
const command = terminalStdin
|
|
? { file: process.execPath, args: ["scripts/rea.mjs", "setup"] }
|
|
: {
|
|
file: "/bin/sh",
|
|
args: [
|
|
"-c",
|
|
'exec "$0" scripts/rea.mjs setup "$@" < /dev/null',
|
|
process.execPath,
|
|
],
|
|
};
|
|
const terminal = spawn(command.file, [...command.args, ...arguments_], {
|
|
cwd: process.cwd(),
|
|
// Client locations such as CODEX_HOME must follow the temporary home.
|
|
env: {
|
|
...process.env,
|
|
...isolatedSetupEnvironment(home),
|
|
REA_LOG_LEVEL: "silent",
|
|
NO_COLOR: "1",
|
|
...environment,
|
|
},
|
|
name: "xterm-256color",
|
|
cols: 120,
|
|
rows: 40,
|
|
});
|
|
let output = "";
|
|
let answered = false;
|
|
terminal.onData((data) => {
|
|
output += data;
|
|
if (
|
|
approval !== undefined &&
|
|
!answered &&
|
|
setupApprovalQuestion.test(output)
|
|
) {
|
|
answered = true;
|
|
terminal.write(approval ? "\r" : "\u001b[C\r");
|
|
}
|
|
});
|
|
const exitCode = await new Promise<number>((resolvePromise, reject) => {
|
|
const timeout = setTimeout(() => {
|
|
terminal.kill();
|
|
reject(new Error(`TTY setup timed out after output:\n${output}`));
|
|
}, 15_000);
|
|
terminal.onExit(({ exitCode: code }) => {
|
|
clearTimeout(timeout);
|
|
resolvePromise(code);
|
|
});
|
|
});
|
|
return { exitCode, output };
|
|
};
|
|
|
|
const manualConnectorFixture = async (): Promise<{
|
|
readonly home: string;
|
|
readonly environment: NodeJS.ProcessEnv;
|
|
}> => {
|
|
const home = await createTestTempDirectory("rea-cli-setup-manual-");
|
|
const bin = join(home, "bin");
|
|
await mkdir(bin);
|
|
const hopper = join(bin, "hopper");
|
|
await writeFile(hopper, "#!/bin/sh\necho 'Hopper Disassembler v6.0.0'\n", {
|
|
mode: 0o755,
|
|
});
|
|
// Linux's executable probe runs ldd before accepting this inert launcher.
|
|
await writeFile(join(bin, "ldd"), "#!/bin/sh\nexit 0\n", { mode: 0o755 });
|
|
for (const runner of ["npx", "npm", "bun"])
|
|
await writeFile(join(bin, runner), "#!/bin/sh\nexit 99\n", {
|
|
mode: 0o755,
|
|
});
|
|
return {
|
|
home,
|
|
environment: {
|
|
PATH: `${bin}:${process.env.PATH ?? ""}`,
|
|
HOPPER_LAUNCHER_PATH: hopper,
|
|
DSH_HOME: join(home, ".dsh"),
|
|
DSH_AGENTS_HOME: join(home, ".dsh-agents"),
|
|
XDG_DATA_HOME: join(home, ".local/share"),
|
|
XDG_CACHE_HOME: join(home, ".cache"),
|
|
XDG_STATE_HOME: join(home, ".local/state"),
|
|
},
|
|
};
|
|
};
|
|
|
|
describe("manual connector approval", () => {
|
|
it.skipIf(process.platform === "win32").each([true, false])(
|
|
"discloses the manual step before approval (apply: %s)",
|
|
async (approved) => {
|
|
const { home, environment } = await manualConnectorFixture();
|
|
const { output, exitCode } = await runSetupInTty(
|
|
home,
|
|
["--client", "grok_bot"],
|
|
approved,
|
|
environment,
|
|
);
|
|
const prompt = output.indexOf("Apply this change?");
|
|
const remediation = manualRegistrationRemediation("grok_bot");
|
|
expect(remediation).toBeDefined();
|
|
expect(prompt, output).toBeGreaterThan(0);
|
|
expect(output.slice(0, prompt)).toContain(remediation);
|
|
const skill = join(
|
|
home,
|
|
".agents/skills/reverse-engineer-anything/SKILL.md",
|
|
);
|
|
if (approved) {
|
|
expect(exitCode, output).toBe(1);
|
|
expect(await readFile(skill, "utf8")).not.toBe("");
|
|
} else {
|
|
expect(exitCode, output).toBe(0);
|
|
await expect(access(skill)).rejects.toMatchObject({ code: "ENOENT" });
|
|
}
|
|
},
|
|
);
|
|
|
|
it.skipIf(process.platform === "win32")(
|
|
"shows the manual step in a TTY dry run",
|
|
async () => {
|
|
const { home, environment } = await manualConnectorFixture();
|
|
const { output, exitCode } = await runSetupInTty(
|
|
home,
|
|
["--dry-run", "--client", "grok_bot"],
|
|
undefined,
|
|
environment,
|
|
);
|
|
const remediation = manualRegistrationRemediation("grok_bot");
|
|
expect(remediation).toBeDefined();
|
|
expect(exitCode, output).toBe(0);
|
|
expect(output).toContain(remediation);
|
|
expect(output).toContain("Dry run complete. No changes were made.");
|
|
},
|
|
);
|
|
});
|
|
|
|
describe("TTY setup dry run", () => {
|
|
it("prints the plan and no-mutation notice for a TTY dry run", async () => {
|
|
const home = await createTestTempDirectory("rea-cli-setup-dry-run-");
|
|
const { exitCode, output } = await runSetupInTty(home, [
|
|
"--dry-run",
|
|
"--client",
|
|
"codex",
|
|
"--skill=false",
|
|
]);
|
|
|
|
expect(exitCode, output).toBe(0);
|
|
expect(output).toContain("CREATE Codex");
|
|
expect(output).toContain(join(home, ".codex/config.toml"));
|
|
expect(output).toContain("Dry run complete. No changes were made.");
|
|
await expect(
|
|
access(join(home, ".codex/config.toml")),
|
|
).rejects.toMatchObject({
|
|
code: "ENOENT",
|
|
});
|
|
});
|
|
|
|
it.skipIf(process.platform === "win32")(
|
|
"shows the unapproved plan it asks a terminal reader to review",
|
|
async () => {
|
|
const home = await createTestTempDirectory("rea-cli-setup-unapproved-");
|
|
const { exitCode, output } = await runSetupInTty(
|
|
home,
|
|
["--client", "codex", "--skill=false"],
|
|
undefined,
|
|
{},
|
|
{ terminalStdin: false },
|
|
);
|
|
|
|
expect(output).toContain(
|
|
"Review the setup plan, then rerun interactively or with --yes.",
|
|
);
|
|
expect(output).toContain("CREATE Codex");
|
|
expect(output).toContain(join(home, ".codex/config.toml"));
|
|
expect(output).toContain("No changes were made.");
|
|
expect(exitCode, output).not.toBe(0);
|
|
await expect(
|
|
access(join(home, ".codex/config.toml")),
|
|
).rejects.toMatchObject({ code: "ENOENT" });
|
|
},
|
|
);
|
|
|
|
it.each([
|
|
{ flag: "--full-output", document: /plannedActions/u },
|
|
{ flag: "--token-count", document: /^\d+$/u },
|
|
])(
|
|
"writes only the requested document for a TTY dry run with $flag",
|
|
async ({ flag, document }) => {
|
|
const home = await createTestTempDirectory("rea-cli-setup-document-");
|
|
const { exitCode, output } = await runSetupInTty(home, [
|
|
"--dry-run",
|
|
"--client",
|
|
"codex",
|
|
"--skill=false",
|
|
flag,
|
|
]);
|
|
|
|
expect(exitCode, output).toBe(0);
|
|
expect(output.trim()).toMatch(document);
|
|
expect(output).not.toContain("Dry run complete. No changes were made.");
|
|
},
|
|
);
|
|
|
|
it("opens the setup rail once when a scoped run starts at approval", async () => {
|
|
const home = await createTestTempDirectory("rea-cli-setup-scoped-");
|
|
const { output } = await runSetupInTty(
|
|
home,
|
|
["--client", "codex", "--skill=false"],
|
|
false,
|
|
);
|
|
|
|
const prompt = output.search(setupApprovalQuestion);
|
|
expect(prompt, output).toBeGreaterThanOrEqual(0);
|
|
const beforePrompt = output.slice(0, prompt);
|
|
expect(beforePrompt.split("REA setup").length - 1, output).toBe(1);
|
|
});
|
|
|
|
it("prints the applied result for a non-interactive TTY setup", async () => {
|
|
const home = await createTestTempDirectory("rea-cli-setup-yes-");
|
|
const { exitCode, output } = await runSetupInTty(home, [
|
|
"--yes",
|
|
"--client",
|
|
"codex",
|
|
"--skill=false",
|
|
]);
|
|
|
|
expect(exitCode, output).toBe(0);
|
|
expect(output).toContain("Restart Codex to load REA.");
|
|
await expect(
|
|
access(join(home, ".codex/config.toml")),
|
|
).resolves.toBeUndefined();
|
|
});
|
|
|
|
it("shows the refusal instead of a blocked skill plan for a TTY dry run", async () => {
|
|
const home = await createTestTempDirectory("rea-cli-setup-linked-dry-run-");
|
|
const managed = join(home, "managed-skill");
|
|
const linked = join(home, ".claude/skills/reverse-engineer-anything");
|
|
const original = "user-managed skill bytes\n";
|
|
await mkdir(managed);
|
|
await writeFile(join(managed, "SKILL.md"), original);
|
|
await mkdir(dirname(linked), { recursive: true });
|
|
await symlink(
|
|
managed,
|
|
linked,
|
|
process.platform === "win32" ? "junction" : "dir",
|
|
);
|
|
|
|
const { exitCode, output } = await runSetupInTty(home, [
|
|
"--dry-run",
|
|
"--client",
|
|
"claude_code",
|
|
]);
|
|
|
|
expect(exitCode, output).toBe(1);
|
|
expect(output).toContain("Skill directory is a symbolic link.");
|
|
expect(output).toContain(linked);
|
|
expect(output).toContain("--skill=false");
|
|
expect(output).not.toContain("REA setup plan");
|
|
expect(output).not.toContain("Install or update the REA skill");
|
|
expect((await lstat(linked)).isSymbolicLink()).toBe(true);
|
|
expect(await readFile(join(managed, "SKILL.md"), "utf8")).toBe(original);
|
|
expect(await readdir(managed)).toEqual(["SKILL.md"]);
|
|
await expect(access(join(home, ".claude.json"))).rejects.toMatchObject({
|
|
code: "ENOENT",
|
|
});
|
|
});
|
|
});
|
|
|
|
cliTest.skipIf(process.platform === "win32")(
|
|
"repairs a Codex timeout without replacing an equivalent caller-selected launcher",
|
|
async ({ cli }) => {
|
|
const home = await createTestTempDirectory("rea-codex-alias-repair-");
|
|
const codexHome = join(home, ".codex");
|
|
const config = join(codexHome, "config.toml");
|
|
const backup = `${config}.rea.backup`;
|
|
const alias = join(home, "rea-launcher-alias.mjs");
|
|
await mkdir(codexHome);
|
|
await symlink(resolve("scripts/rea.mjs"), alias, "file");
|
|
const original = [
|
|
"# Caller-owned Codex approval policy",
|
|
'approval_policy = "on-request"',
|
|
'sandbox_mode = "read-only"',
|
|
"",
|
|
"[mcp_servers.rea]",
|
|
`command = ${JSON.stringify(process.execPath)}`,
|
|
`args = ${JSON.stringify([alias, "mcp"])}`,
|
|
"startup_timeout_sec = 0",
|
|
"tool_timeout_sec = 900",
|
|
'default_tools_approval_mode = "prompt"',
|
|
"",
|
|
"[mcp_servers.rea.tools.open_binary]",
|
|
'approval_mode = "approve"',
|
|
"output_token_limit = 2048",
|
|
"",
|
|
].join("\n");
|
|
await writeFile(config, original);
|
|
const setup = (approval: "--dry-run" | "--yes") =>
|
|
cli.run({
|
|
arguments: [
|
|
"setup",
|
|
"--client",
|
|
"codex",
|
|
"--no-skill",
|
|
approval,
|
|
"--json",
|
|
],
|
|
cwd: home,
|
|
environment: {
|
|
HOME: home,
|
|
USERPROFILE: home,
|
|
CODEX_HOME: codexHome,
|
|
XDG_CONFIG_HOME: join(home, ".config"),
|
|
XDG_DATA_HOME: join(home, ".local", "share"),
|
|
XDG_CACHE_HOME: join(home, ".cache"),
|
|
},
|
|
});
|
|
|
|
const planned = await setup("--dry-run");
|
|
expect(planned.exitCode, planned.stderr).toBe(0);
|
|
expect(planned.json).toMatchObject({
|
|
status: "planned",
|
|
plannedActions: [
|
|
expect.objectContaining({
|
|
id: "configure_client:codex",
|
|
operation: "update",
|
|
target: config,
|
|
backupPath: backup,
|
|
}),
|
|
],
|
|
});
|
|
expect(await readFile(config, "utf8")).toBe(original);
|
|
await expect(access(backup)).rejects.toMatchObject({ code: "ENOENT" });
|
|
|
|
const applied = await setup("--yes");
|
|
expect(applied.exitCode, applied.stderr).toBe(0);
|
|
expect(applied.json).toMatchObject({ status: "ready" });
|
|
const repaired = await readFile(config, "utf8");
|
|
expect(parseToml(repaired)).toMatchObject({
|
|
approval_policy: "on-request",
|
|
sandbox_mode: "read-only",
|
|
mcp_servers: {
|
|
rea: {
|
|
command: process.execPath,
|
|
args: [alias, "mcp"],
|
|
startup_timeout_sec: 30,
|
|
tool_timeout_sec: 900,
|
|
default_tools_approval_mode: "prompt",
|
|
tools: {
|
|
open_binary: { approval_mode: "approve", output_token_limit: 2048 },
|
|
},
|
|
},
|
|
},
|
|
});
|
|
expect(await readFile(backup, "utf8")).toBe(original);
|
|
expect((await lstat(alias)).isSymbolicLink()).toBe(true);
|
|
|
|
const repeated = await setup("--yes");
|
|
expect(repeated.exitCode, repeated.stderr).toBe(0);
|
|
expect(repeated.json).toMatchObject({
|
|
status: "ready",
|
|
plannedActions: [],
|
|
appliedActions: [],
|
|
});
|
|
expect(await readFile(config, "utf8")).toBe(repaired);
|
|
expect(await readFile(backup, "utf8")).toBe(original);
|
|
},
|
|
);
|
|
|
|
describe("interactive setup journey", () => {
|
|
it("shows detected and absent clients without preselecting detected clients", async () => {
|
|
const result = await runJourney(
|
|
[
|
|
step("Which agents should use REA?", "\u001b[B"),
|
|
step("Not detected · configuration is still available", "\r"),
|
|
],
|
|
false,
|
|
[actions[0]],
|
|
);
|
|
expect(result.output).toContain("Detected: Codex");
|
|
expect(result.output).toContain(
|
|
"Not detected · configuration is still available",
|
|
);
|
|
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("selects an absent OpenCode client and bundles its skill", async () => {
|
|
const result = await runJourney(
|
|
[
|
|
step("Which agents should use REA?", "\u001b[B \r"),
|
|
step("Apply these 2 changes?", "\r"),
|
|
],
|
|
false,
|
|
[
|
|
{
|
|
...actions[0],
|
|
id: "configure_client:opencode",
|
|
label: "OpenCode",
|
|
target: "/isolated/.config/opencode/opencode.json",
|
|
},
|
|
actions[1],
|
|
],
|
|
);
|
|
expect(result.output).toContain("CREATE OpenCode");
|
|
expect(result.decision.selectedActionIds).toEqual([
|
|
"configure_client:opencode",
|
|
"install_skill",
|
|
]);
|
|
expect(result.decision.approved).toBe(true);
|
|
});
|
|
|
|
it("shows the selected changes before consent and leaves Hopper unselected", async () => {
|
|
const approvalPrompt = "Apply these 2 changes?";
|
|
const result = await runJourney(
|
|
[
|
|
step("Which agents should use REA?", " \r"),
|
|
step("Install Hopper for deep binary analysis?", "\r"),
|
|
step(approvalPrompt, "\r"),
|
|
],
|
|
false,
|
|
[
|
|
{
|
|
...actions[0],
|
|
operation: "update",
|
|
backupPath: "/isolated/.codex/config.toml.bak",
|
|
commands: ["npx -y rea-agents@3.2.1 mcp"],
|
|
},
|
|
actions[1],
|
|
actions[2],
|
|
],
|
|
);
|
|
const preflight = result.output.split(approvalPrompt, 1)[0];
|
|
expect(preflight).toContain("UPDATE Codex");
|
|
expect(preflight).toMatch(/\/isolated\/\.codex\/config\.toml\r?\n/u);
|
|
expect(preflight).toContain("backup: /isolated/.codex/config.toml.bak");
|
|
expect(preflight).toContain("command: npx -y rea-agents@3.2.1 mcp");
|
|
expect(result.decision).toEqual({
|
|
approved: true,
|
|
selectedActionIds: ["configure_client:codex", "install_skill"],
|
|
});
|
|
});
|
|
|
|
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("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[0], id: "configure_client:opencode", label: "OpenCode" }],
|
|
);
|
|
expect(result.decision.selectedActionIds).toEqual([
|
|
"configure_client:opencode",
|
|
]);
|
|
});
|
|
|
|
it("preselects only a prior REA registration", async () => {
|
|
const result = await runJourney(
|
|
[
|
|
step("Which agents should use REA?", "\r"),
|
|
step("Apply these 2 changes?", "\r"),
|
|
],
|
|
false,
|
|
agentActions,
|
|
{ initialClientIds: ["codex"] },
|
|
);
|
|
expect(result.decision.selectedActionIds).toEqual([
|
|
"configure_client:codex",
|
|
"install_skill",
|
|
]);
|
|
});
|
|
});
|
|
|
|
describe("interactive setup client hints", () => {
|
|
const manual =
|
|
"Found migrated Claude Desktop storage. Register REA manually in the active file.";
|
|
const repairOverride =
|
|
"Invalid PI_CODING_AGENT_DIR: encoded slash. Repair the override before configuring Pi.";
|
|
const repairConfiguration =
|
|
"Existing configuration needs repair before setup";
|
|
it.for([
|
|
{
|
|
name: "claude_desktop",
|
|
format: "json",
|
|
status: "unknown",
|
|
configPathError: manual,
|
|
expected: manual,
|
|
},
|
|
{
|
|
name: "claude_desktop",
|
|
format: "json",
|
|
status: "invalid",
|
|
configPathError: manual,
|
|
expected: manual,
|
|
},
|
|
{
|
|
name: "pi",
|
|
format: "pi",
|
|
status: "unknown",
|
|
configPathError: repairOverride,
|
|
expected: repairOverride,
|
|
},
|
|
{
|
|
name: "codex",
|
|
format: "toml",
|
|
status: "invalid",
|
|
configPathError: undefined,
|
|
expected: repairConfiguration,
|
|
},
|
|
] as const)(
|
|
"shows the recovery for $name when setup reports $status",
|
|
async ({ name, format, status, configPathError, expected }) => {
|
|
const state: SetupClientState = {
|
|
client: {
|
|
name,
|
|
registrationProfile: supportedClientRegistrationProfile(name),
|
|
format,
|
|
configPath: join(name, "config"),
|
|
...(configPathError === undefined ? {} : { configPathError }),
|
|
},
|
|
detected: true,
|
|
configured: false,
|
|
status,
|
|
};
|
|
const result = await runJourney(
|
|
[step("Which agents should use REA?", "\r")],
|
|
false,
|
|
[actions[0]],
|
|
{ states: [state, clientStates[1]] },
|
|
);
|
|
expect(result.output).toContain(expected);
|
|
expect(result.decision.selectedActionIds).toEqual([]);
|
|
},
|
|
);
|
|
});
|
|
|
|
describe("interactive setup completion", () => {
|
|
it.each([
|
|
{ npmCommand: "", userAgent: "", launcher: "rea" },
|
|
{
|
|
npmCommand: "exec",
|
|
userAgent: "npm/10.9.0 node/v24.11.0 linux x64",
|
|
launcher: "npx rea-agents",
|
|
},
|
|
{
|
|
npmCommand: "exec",
|
|
userAgent: "bun/1.4.2 npm/? node/v26.3.0 linux x64",
|
|
launcher: "bunx rea-agents",
|
|
},
|
|
])(
|
|
"prints an available next command for $launcher invocation",
|
|
async ({ npmCommand, userAgent, launcher }) => {
|
|
const { stderr } = await execute(
|
|
process.execPath,
|
|
[
|
|
"--input-type=module",
|
|
"--eval",
|
|
[
|
|
'import { renderInteractiveSetupResult } from "./dist/cli/interactiveSetup.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: {
|
|
...Object.fromEntries(
|
|
Object.entries(process.env).filter(
|
|
([key]) =>
|
|
!["npm_command", "npm_config_user_agent"].includes(
|
|
key.toLowerCase(),
|
|
),
|
|
),
|
|
),
|
|
npm_command: npmCommand,
|
|
npm_config_user_agent: userAgent,
|
|
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: ${launcher} analyze /path/to/app`);
|
|
expect(stderr).toContain(
|
|
'Try in Codex: "Explain how a feature works in /path/to/app and show the evidence."',
|
|
);
|
|
},
|
|
);
|
|
|
|
it("prints IDA and JADX with their product spellings", async () => {
|
|
const { stderr } = await execute(
|
|
process.execPath,
|
|
[
|
|
"--input-type=module",
|
|
"--eval",
|
|
[
|
|
'import { renderInteractiveSetupResult } from "./dist/cli/interactiveSetup.js";',
|
|
"renderInteractiveSetupResult({",
|
|
' status: "ready",',
|
|
" plannedActions: [],",
|
|
" appliedActions: [],",
|
|
" clients: {},",
|
|
" doctor: {",
|
|
" healthy: true,",
|
|
' availableProviders: ["hopper", "ghidra", "ida", "jadx", "kuna"],',
|
|
" checks: [],",
|
|
" },",
|
|
"}, {});",
|
|
].join("\n"),
|
|
],
|
|
{ cwd: process.cwd(), env: { ...process.env, NO_COLOR: "1" } },
|
|
);
|
|
|
|
expect(stderr).toContain(
|
|
"Deep analysis: Hopper, Ghidra, IDA, JADX, and Kuna",
|
|
);
|
|
expect(stderr).not.toContain("Ida");
|
|
expect(stderr).not.toContain("Jadx");
|
|
});
|
|
|
|
it("prints retained cleanup resources without relying on paths in remediation", async () => {
|
|
const resources = ["/fixture/owned backup", "/fixture/临时目录"];
|
|
const result: SetupResult = {
|
|
status: "needs_human",
|
|
code: "cleanup_failed",
|
|
plannedActions: [],
|
|
appliedActions: [],
|
|
clients: {},
|
|
clientStates: [],
|
|
doctor: {
|
|
healthy: true,
|
|
environment_healthy: true,
|
|
availableProviders: [],
|
|
scope: {
|
|
mode: "explicit",
|
|
clients: [],
|
|
providers: [],
|
|
skill: false,
|
|
target: null,
|
|
},
|
|
},
|
|
remediation: "Owned descriptor remains busy",
|
|
cleanup: { reason: "Owned descriptor remains busy", resources },
|
|
};
|
|
const { stderr } = await execute(
|
|
process.execPath,
|
|
[
|
|
"--input-type=module",
|
|
"--eval",
|
|
'import { renderInteractiveSetupResult } from "./dist/cli/interactiveSetup.js";\n' +
|
|
`renderInteractiveSetupResult(${JSON.stringify(result)}, {});`,
|
|
],
|
|
{ cwd: process.cwd(), env: { ...process.env, NO_COLOR: "1" } },
|
|
);
|
|
expect(stderr).toContain(result.remediation);
|
|
for (const resource of resources) expect(stderr).toContain(resource);
|
|
});
|
|
});
|
|
|
|
interface JourneyStep {
|
|
readonly prompt: string;
|
|
readonly input: string;
|
|
}
|
|
|
|
interface JourneyResult {
|
|
readonly output: string;
|
|
readonly decision: z.infer<typeof decisionSchema>;
|
|
}
|
|
|
|
const step = (prompt: string, input: string): JourneyStep => ({
|
|
prompt,
|
|
input,
|
|
});
|
|
|
|
const runJourney = async (
|
|
steps: readonly JourneyStep[],
|
|
accessible = false,
|
|
journeyActions: readonly object[] = agentActions,
|
|
{
|
|
initialClientIds = [],
|
|
states = clientStates,
|
|
}: {
|
|
readonly initialClientIds?: readonly string[];
|
|
readonly states?: readonly SetupClientState[];
|
|
} = {},
|
|
): Promise<JourneyResult> => {
|
|
const isolatedHome = await createTestTempDirectory("rea-cli-setup-test-");
|
|
const script = [
|
|
'import { confirmInteractiveSetup, createSetupJourney } from "./dist/cli/interactiveSetup.js";',
|
|
"const journey = createSetupJourney();",
|
|
`const actions = ${JSON.stringify(journeyActions)};`,
|
|
`const context = ${JSON.stringify({ stage: "select", clientStates: states, selectedClientIds: initialClientIds, clientSelectionAllowed: true })};`,
|
|
`let decision = await confirmInteractiveSetup(actions, ${JSON.stringify(accessible)}, context, undefined, journey);`,
|
|
"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 }, undefined, journey);`,
|
|
"}",
|
|
`process.stdout.write(${JSON.stringify(`\n${decisionMarker}`)} + JSON.stringify(decision) + "\\n");`,
|
|
].join("\n");
|
|
|
|
return new Promise<JourneyResult>((resolvePromise, reject) => {
|
|
let output = "";
|
|
let nextStep = 0;
|
|
let settled = false;
|
|
const terminal = spawn(
|
|
process.execPath,
|
|
["--input-type=module", "--eval", script],
|
|
{
|
|
cwd: process.cwd(),
|
|
env: {
|
|
...process.env,
|
|
HOME: isolatedHome,
|
|
USERPROFILE: isolatedHome,
|
|
NO_COLOR: "1",
|
|
TERM: "xterm-256color",
|
|
},
|
|
name: "xterm-256color",
|
|
cols: 120,
|
|
rows: 40,
|
|
},
|
|
);
|
|
const timeout = setTimeout(() => {
|
|
terminal.kill();
|
|
finish(new Error(`Timed out after output:\n${output}`));
|
|
}, 10_000);
|
|
|
|
terminal.onData((data) => {
|
|
output += data;
|
|
const pending = steps[nextStep];
|
|
if (pending !== undefined && output.includes(pending.prompt)) {
|
|
nextStep += 1;
|
|
terminal.write(pending.input);
|
|
}
|
|
});
|
|
terminal.onExit(({ exitCode }) => {
|
|
if (exitCode !== 0) {
|
|
finish(
|
|
new Error(`Setup journey exited ${String(exitCode)}:\n${output}`),
|
|
);
|
|
return;
|
|
}
|
|
if (nextStep !== steps.length) {
|
|
finish(new Error(`Setup journey missed an interaction:\n${output}`));
|
|
return;
|
|
}
|
|
const markerIndex = output.lastIndexOf(decisionMarker);
|
|
if (markerIndex === -1) {
|
|
finish(new Error(`Setup journey returned no decision:\n${output}`));
|
|
return;
|
|
}
|
|
const raw = output.slice(markerIndex + decisionMarker.length);
|
|
const jsonStart = raw.indexOf("{");
|
|
const jsonEnd = raw.lastIndexOf("}");
|
|
const serialized =
|
|
jsonStart !== -1 && jsonEnd !== -1 && jsonEnd > jsonStart
|
|
? raw.slice(jsonStart, jsonEnd + 1)
|
|
: raw.split(/\r?\n/u, 1)[0];
|
|
if (serialized === undefined) {
|
|
finish(
|
|
new Error(`Setup journey returned an empty decision:\n${output}`),
|
|
);
|
|
return;
|
|
}
|
|
try {
|
|
finish(undefined, {
|
|
output,
|
|
decision: decisionSchema.parse(JSON.parse(serialized)),
|
|
});
|
|
} catch (cause: unknown) {
|
|
finish(cause instanceof Error ? cause : new Error(String(cause)));
|
|
}
|
|
});
|
|
|
|
function finish(error?: Error, result?: JourneyResult): void {
|
|
if (settled) return;
|
|
settled = true;
|
|
clearTimeout(timeout);
|
|
void rm(isolatedHome, { recursive: true, force: true }).finally(() => {
|
|
if (error !== undefined) reject(error);
|
|
else if (result !== undefined) resolvePromise(result);
|
|
else reject(new Error("Setup journey completed without a result"));
|
|
});
|
|
}
|
|
});
|
|
};
|