Files
reverse-engineering-anything/tests/boundary/cli/webScriptSelectionCli.test.ts
T
Ysopwnableandgensokyo-dev 62014b566d refactor(cli)!: dispatch commands through REA-owned execution
Run ordinary CLI commands through REA's registry, argv parser and result owner.
Remove Incur, the second admission parse, SDK error middleware, output capture
and redundant command traversal. Preserve explicit redaction, publication
receipts, incremental output, terminal notice eligibility and drain ownership.
Migrate fixtures to real registrations and retain the derived-source notices.

Validation includes unchanged public parity goldens, public and lifecycle
regressions, repaired fixture consumers, real TTY base comparisons, exports
beyond the engine string limit, four schema catalogs and final static/docs
checks. Native provider and optional validator coverage limits are in the PR.

Fixes #11654. Fixes #10583. Refs #11682, #11476 and #10511.

BREAKING CHANGE: Markdown argument diagnostics use REA's literal escaping,
table widths and token counts. Flag-shaped unknown MCP subcommands honor the
selected format. Completion --schema/--version routes use the canonical
REA-owned hook rather than the retired SDK generator. Refresh affected literal
snapshots and regenerate completion hooks with rea completions <shell>.

Co-authored-by: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com>
2026-11-16 13:56:34 +00:00

211 lines
6.9 KiB
TypeScript

import { createCommandCli } from "../../support/cli/commandCli.js";
import { cliCommand } from "../../../src/cli/commandRegistry.js";
import { access, mkdir, readdir, symlink, writeFile } from "node:fs/promises";
import { join } from "node:path";
import pino from "pino";
import { expect, it, vi } from "vitest";
import { registerWebScriptCommands } from "../../../src/cli/webScriptCommands.js";
import * as webScriptExport from "../../../src/application/WebScriptExportService.js";
import { cliCommandFor } from "../../../src/contracts/cliCommandNames.js";
import { AnalysisCancelledError } from "../../../src/domain/analysisErrorCore.js";
import { err, ok } from "../../../src/domain/result.js";
import { ArtifactResourceScope } from "../../../src/resources/ArtifactResourceScope.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import {
scriptCaptureEvidenceFixture,
scriptScenarioFixture,
} from "../../fixtures/webScriptCapture.js";
import { cliTest } from "../../support/cli/cliFixture.js";
const registeredExportCommand = () => {
const cli = createCommandCli();
registerWebScriptCommands(cli, pino({ enabled: false }));
return cliCommand(cli, cliCommandFor("export_web_scripts"))!.definition;
};
it("forwards an interrupt into the export workflow and reports cancellation", async () => {
const command = registeredExportCommand();
const exported = vi
.spyOn(webScriptExport, "exportWebScripts")
.mockImplementation(async (_input, _resources, options) => {
process.emit("SIGINT");
return err(
new AnalysisCancelledError("export_web_scripts", {
cause: options?.signal?.reason,
}),
);
});
const previousExitCode = process.exitCode;
try {
const output = await command.run({
formatExplicit: false,
options: {},
args: {
capturePath: "/unused/capture.json",
outputDirectory: "/unused/out",
},
});
expect(exported.mock.calls[0]?.[2]?.signal?.aborted).toBe(true);
expect(output).toMatchObject({ code: "cancelled" });
expect(process.exitCode).toBe(130);
} finally {
exported.mockRestore();
process.exitCode = previousExitCode;
}
});
it.each(["cleanup failure", "cancellation during cleanup"] as const)(
"retains exported Evidence on %s",
async (outcome) => {
const command = registeredExportCommand();
const evidence = scriptCaptureEvidenceFixture();
const exported = vi
.spyOn(webScriptExport, "exportWebScripts")
.mockResolvedValue(ok(evidence));
const close = vi
.spyOn(ArtifactResourceScope.prototype, "close")
.mockImplementation(async () => {
if (outcome === "cleanup failure") throw new Error("close denied");
process.emit("SIGINT");
});
const previousExitCode = process.exitCode;
try {
const output = await command.run({
formatExplicit: false,
options: {},
args: {
capturePath: "/unused/capture.json",
outputDirectory: "/unused/out",
},
});
expect(close).toHaveBeenCalledOnce();
expect(output).toMatchObject({
error: "Script export failed",
code:
outcome === "cleanup failure" ? "cleanup_incomplete" : "cancelled",
details: { partial_observation: evidence },
});
} finally {
exported.mockRestore();
close.mockRestore();
process.exitCode = previousExitCode;
}
},
);
it("closes export resources when the operation throws", async () => {
const command = registeredExportCommand();
const exported = vi
.spyOn(webScriptExport, "exportWebScripts")
.mockRejectedValue(new Error("unexpected export failure"));
const close = vi
.spyOn(ArtifactResourceScope.prototype, "close")
.mockResolvedValue();
try {
const output = await command.run({
formatExplicit: false,
options: {},
args: {
capturePath: "/unused/capture.json",
outputDirectory: "/unused/out",
},
});
expect(close).toHaveBeenCalledOnce();
expect(output).toMatchObject({
error: "Script export failed",
details: { operation: "export_web_scripts" },
});
} finally {
exported.mockRestore();
close.mockRestore();
}
});
cliTest.skipIf(process.platform === "win32")(
"exits with a capture_path invalid_request for a named pipe before publishing output",
async ({ cli, processes }) => {
const root = await createTestTempDirectory("rea-script-selection-cli-");
const capturePath = join(root, "capture.pipe");
const outputDirectory = join(root, "export");
const created = await processes.run("mkfifo", [capturePath]);
expect(created.exitCode).toBe(0);
const response = await cli.run({
arguments: ["export-web-scripts", capturePath, outputDirectory, "--json"],
environment: { REA_LOG_LEVEL: "silent" },
});
expect(response.exitCode).toBe(1);
expect(response.signal).toBeNull();
expect(response.json).toMatchObject({
error: "Script export failed",
code: "invalid_request",
details: {
operation: "export_web_scripts",
issues: [
{
path: ["capturePath"],
reason: "invalid_value",
message: expect.stringContaining("regular file"),
},
],
},
});
expect(response.stdout).toContain(capturePath);
await expect(access(outputDirectory)).rejects.toMatchObject({
code: "ENOENT",
});
},
);
cliTest(
"refuses an existing output directory or link as invalid output_directory input",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-script-export-existing-");
const capturePath = join(root, "capture.json");
await writeFile(capturePath, JSON.stringify(scriptScenarioFixture()));
const retained = join(root, "retained");
await mkdir(retained);
await writeFile(join(retained, "marker.txt"), "keep");
const link = join(root, "output-link");
await symlink(
retained,
link,
process.platform === "win32" ? "junction" : "dir",
);
for (const outputDirectory of [retained, link]) {
const response = await cli.run({
arguments: [
"export-web-scripts",
capturePath,
outputDirectory,
"--json",
],
environment: { REA_LOG_LEVEL: "silent" },
});
expect(response.exitCode).toBe(1);
expect(response.json).toMatchObject({
code: "invalid_request",
category: "invalid_input",
recovery: {
kind: "inspect_input_contract",
operation: "export_web_scripts",
},
details: {
operation: "export_web_scripts",
issues: [
{
path: ["outputDirectory"],
reason: "invalid_value",
message: "Output root already exists",
},
],
},
});
}
expect(await readdir(retained)).toEqual(["marker.txt"]);
},
);