Files
morlutoandCursor Agent 2bf347dee6 fix(cli): reject invalid inline values and honor requested output on terminals (#14763)
* 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>
2026-11-26 12:15:17 -05:00

300 lines
11 KiB
TypeScript

import { cliCommand } from "../../../src/cli/commandRegistry.js";
import { createCommandCli } from "../../support/cli/commandCli.js";
import { unknownTarget } from "../../../src/domain/targetIdentity.js";
import { closeVerifierResources } from "../../../scripts/lib/verifier-cleanup.mjs";
import { z } from "zod";
import pino from "pino";
import { readFile, readdir, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect, it, onTestFinished, vi } from "vitest";
import { registerReverseEngineeringCommands } from "../../../src/cli/reverseEngineeringCommands.js";
import type { CliInstance } from "../../../src/cli/types.js";
import {
CLI_COMMANDS,
cliCommandFor,
} from "../../../src/contracts/cliCommandNames.js";
import {
createEvidence,
parseEvidence,
evidenceSchema,
} from "../../../src/domain/evidence.js";
import { parseEvidenceBundle } from "../../../src/domain/evidenceBundle.js";
import { ok } from "../../../src/domain/result.js";
import { OwnedStagedOutput } from "../../../src/filesystem/OwnedStagedOutput.js";
import { GdbSessionManager } from "../../../src/gdb/GdbSessionManager.js";
import { TestReverseEngineeringService } from "../../support/reverseEngineeringService.js";
import { ownedOutput } from "../../support/reverseEngineeringCompositionFixtures.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
const kinds = ["objdump", "architectures", "gdb"] as const;
const fixture = async (kind: (typeof kinds)[number]) => {
const directory = await createTestTempDirectory("rea-command-delivery-");
const path = join(directory, "input.bin");
await writeFile(path, "local CLI publication fixture");
const runProvider = vi.fn(async () =>
ownedOutput("opaque provider output\n", "provider diagnostic\n"),
);
const service = new TestReverseEngineeringService({
environment: {},
runOwned: runProvider,
});
const closeService = vi.spyOn(service, "close");
const manager = new GdbSessionManager({ platform: "linux", environment: {} });
const sessionId = "00000000-0000-4000-8000-000000000001";
const report = {
command: "show architecture",
mi: "5^done",
records: ['~"architecture\\n"', "unknown record", "5^done"],
console: '~"architecture\\n"',
target: "",
log: "",
completion_status: "complete" as const,
output_truncated: false,
};
const parent = createEvidence(
unknownTarget("not-observed"),
{ id: "gdb", name: "GDB", version: null },
{
operation: "gdb_console",
parameters: { session_id: sessionId, command: report.command },
result: report,
},
);
const start = vi
.spyOn(manager, "start")
.mockResolvedValue(ok({ session_id: sessionId, mi_version: "mi3" }));
vi.spyOn(manager, "execute").mockResolvedValue(
ok({ result: report, evidence: parent }),
);
const close = vi
.spyOn(manager, "close")
.mockResolvedValue(ok({ target_state: "none_observed" }));
const closeAll = vi.spyOn(manager, "closeAll").mockResolvedValue(undefined);
const createManager = vi.fn(() => manager);
const cli = createCommandCli();
registerReverseEngineeringCommands(
cli as unknown as CliInstance,
pino({ enabled: false }),
{},
createManager,
() => service,
);
onTestFinished(() =>
closeVerifierResources([() => service.close(), () => manager.closeAll()]),
);
const commandName =
kind === "gdb"
? CLI_COMMANDS.debugWithGdb
: kind === "objdump"
? cliCommandFor("inspect_with_objdump")
: CLI_COMMANDS.listObjdumpArchitectures;
const command = cliCommand(cli, commandName)?.definition;
if (command === undefined) throw new Error("CLI command was not registered");
// A command without positionals registers no argument schema.
const argsSchema: unknown = Reflect.get(command, "args") ?? z.object({});
const optionsSchema = Reflect.get(command, "options");
const execute = Reflect.get(command, "run");
if (
!(argsSchema instanceof z.ZodObject) ||
!(optionsSchema instanceof z.ZodObject) ||
typeof execute !== "function"
)
throw new Error("Missing CLI command schemas or callback");
const args =
kind === "gdb"
? { command: report.command }
: kind === "objdump"
? { path, operation: "file_headers" }
: {};
const invoke = async (options: Record<string, unknown>): Promise<unknown> =>
execute({
args: argsSchema.parse(args),
structuredOutput: false,
options: optionsSchema.parse({
...(kind === "gdb" ? { inferiorTty: "/dev/pts/caller-fixture" } : {}),
...options,
}),
});
return {
directory,
invoke,
runProvider,
createManager,
start,
close,
closeAll,
closeService,
parent,
report,
};
};
it.each(kinds)(
"publishes %s summaries with exact complete parents",
async (kind) => {
const f = await fixture(kind);
const destination = join(f.directory, "complete.json");
const output = z
.object({
summary: evidenceSchema,
evidence_bundle: z.object({ path: z.string(), bytes: z.number() }),
})
.parse(
await f.invoke({ detail: "summary", evidence_output: destination }),
);
const selected = parseEvidence(output.summary);
const serialized = await readFile(destination, "utf8");
const bundle = JSON.parse(serialized);
expect(output.evidence_bundle.bytes).toBe(Buffer.byteLength(serialized));
expect(bundle.records).toHaveLength(1);
const parent = parseEvidence(bundle.records[0]);
expect(parent.raw_result).toBeNull();
expect(selected.normalized_result).toMatchObject({
parent_evidence_id: parent.evidence_id,
source_parameters: parent.parameters,
source_provider: parent.provider,
});
expect(selected.raw_result).toBeNull();
expect(output.evidence_bundle.path).toBe(destination);
if (kind === "gdb") {
expect(parent).toEqual(f.parent);
expect(selected.normalized_result).toMatchObject({
artifact: null,
// Stream records are reported by size, not repeated.
summary: {
records: ["unknown record", "5^done"],
available_counts: { records: 3, stream_records: 1 },
},
});
expect(f.close).toHaveBeenCalledOnce();
expect(f.closeAll).toHaveBeenCalledOnce();
} else {
const { stdout, stderr, ...facts } = z
.object({ stdout: z.string(), stderr: z.string() })
.passthrough()
.parse(parent.normalized_result);
expect(selected.normalized_result).toMatchObject({
summary: {
...facts,
available_counts: {
stdout_utf16_units: stdout.length,
stderr_utf16_units: stderr.length,
},
},
});
expect(f.runProvider).toHaveBeenCalledOnce();
expect(f.closeService).toHaveBeenCalledOnce();
}
if (kind !== "objdump") {
expect(parent.subject.identity.kind).toBe("unknown");
expect(selected.subject.identity.kind).toBe("unknown");
expect(selected.normalized_result).toMatchObject({ artifact: null });
}
},
);
it.each(["objdump", "gdb"] as const)(
"rejects %s summary without a destination before provider work",
async (kind) => {
const f = await fixture(kind);
const output = await f.invoke({ detail: "summary" });
expect(output).toMatchObject({ code: "invalid_request" });
expect(JSON.stringify(output)).toContain("evidence_output");
expect(f.createManager).not.toHaveBeenCalled();
expect(f.start).not.toHaveBeenCalled();
expect(f.runProvider).not.toHaveBeenCalled();
},
);
it.each(["objdump", "gdb"] as const)(
"preserves an existing %s destination and reports publication failure with source Evidence",
async (kind) => {
const f = await fixture(kind);
const destination = join(f.directory, "existing.json");
const original = Buffer.from("caller-selected content\n");
await writeFile(destination, original);
const output = await f.invoke({
detail: "summary",
evidence_output: destination,
});
expect(Buffer.compare(await readFile(destination), original)).toBe(0);
expect(output).toHaveProperty("code");
expect(output).not.toHaveProperty("summary");
expect(output).toHaveProperty("details.partial_observation.evidence_id");
if (kind === "gdb") {
expect(f.close).toHaveBeenCalledOnce();
expect(f.closeAll).toHaveBeenCalledOnce();
} else expect(f.closeService).toHaveBeenCalledOnce();
},
);
const interruptAt = (method: "assertReadyForPublication" | "close"): void => {
const original = OwnedStagedOutput.prototype[method];
const seam = vi
.spyOn(OwnedStagedOutput.prototype, method)
.mockImplementationOnce(async function (
this: OwnedStagedOutput,
...arguments_: Parameters<OwnedStagedOutput[typeof method]>
) {
await Reflect.apply(original, this, arguments_);
process.emit("SIGINT");
});
onTestFinished(() => {
seam.mockRestore();
process.exitCode = undefined;
});
};
it.each(["objdump", "gdb"] as const)(
"keeps the committed %s receipt when SIGINT arrives during final staging cleanup",
async (kind) => {
const f = await fixture(kind);
const destination = join(f.directory, "complete.json");
interruptAt("close");
const output = await f.invoke({
detail: "summary",
evidence_output: destination,
});
expect(process.exitCode).toBe(130);
const serialized = await readFile(destination, "utf8");
const parent = parseEvidenceBundle(JSON.parse(serialized)).records[0]!;
expect(output).toMatchObject({
code: "cancelled",
details: {
diagnostics: {
evidence_bundle: {
path: destination,
bytes: Buffer.byteLength(serialized),
},
},
partial_observation: {
evidence_links: [parent.evidence_id],
normalized_result: { parent_evidence_id: parent.evidence_id },
},
},
});
expect(await readdir(f.directory)).not.toContainEqual(
expect.stringMatching(/^\.rea-write-/u),
);
},
);
it.each(["objdump", "gdb"] as const)(
"publishes no %s bundle or receipt when SIGINT arrives before commit",
async (kind) => {
const f = await fixture(kind);
const destination = join(f.directory, "complete.json");
interruptAt("assertReadyForPublication");
const output = await f.invoke({
detail: "summary",
evidence_output: destination,
});
expect(process.exitCode).toBe(130);
expect(output).toMatchObject({ code: "cancelled" });
expect(output).not.toHaveProperty("details.diagnostics");
expect(JSON.stringify(output)).not.toContain(destination);
expect(output).toHaveProperty("details.partial_observation.raw_result");
expect(await readdir(f.directory)).toEqual(["input.bin"]);
},
);