Files
reverse-engineering-anything/tests/acceptance/applications/pythonPycViews.test.ts
T
morluto b3657c557f perf(tests): run plain CLI commands on the file's shared process (#10412)
* refactor(cli): run one-shot commands through one shared owner

scripts/rea.mjs and the test CLI session worker each implemented the
one-shot command sequence: argument normalization, output admission,
configuration errors, version documents, the Amp scope refusal, and
result delivery. The worker copy had drifted: it never rendered
formatted version reports or the Amp refusal.

Move the sequence into src/cliOneShot.ts. Both callers supply a host
for their streams, exit and resource ownership. The launcher keeps
closed-pipe status, worker shutdown and process exit; the session
worker captures output per command.

The cliOutput bundle entry is superseded and removed. The dispatcher
test now replaces only the command runtime, so output admission runs
production code. A new parity test compares the file session with a
fresh process.

* test(cli): bundle the one-shot entry in the runtime bundle fixture

* perf(tests): run plain CLI commands on the file's shared process

`cli.run` in `cliTest` files started a fresh compiled CLI for every
command, about 0.45s and 260 MB each before any work. The file-scoped
session already existed, but callers had to opt in through
`runFileCli` or `sharedCliRun`, so 1,300 call sites still spawned.

Make the fixture choose: `cli.run` uses the shared process when it
reports the command exactly as a fresh process would, and starts one
otherwise (stdin, explicit deadlines, MCP and MCP doctor routing,
NODE_OPTIONS, or enabled logging). `freshProcess: true` keeps
explicit process-level checks. The session worker now presents the
launcher's entrypoint, so registration identity matches a fresh
process.

`runFileCli` and `sharedCliRun` are superseded and removed; their
call sites use `cli.run`, and paired fresh/shared checks use
`freshProcess`.

* style(tests): format the managed member summary call site

* test(cli): give each shared-session command an empty stdin

The shared CLI process reads session frames from its own stdin. A
command that reads stdin without supplied input, such as
`compare-wasm-interfaces - --json`, read that pipe and hung, where a
fresh process receives EOF. The worker now presents an ended, empty
stdin to each command and restores its own afterwards.

The parity test compared the routed path with itself after cli.run
began choosing the session. It now compares a fresh process with the
session directly, including the `mcp add` refusal and a command
reading absent stdin.

* test(cli): keep default command logging and launcher checks on fresh processes

environment-serve and environment-build log at info when REA_LOG_LEVEL is
unset, through a logger that writes to stderr directly. The shared CLI
process captures only process.stderr writes, so routed runs lost those
lines. Declare the default-logging commands beside the command names,
have infoLogger read that set, and start a fresh process for them.

The log-level precedence checks compared the shared process with itself
after routing; their fresh side now passes freshProcess: true.
2026-11-14 14:28:08 +08:00

257 lines
8.3 KiB
TypeScript

import { rm, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect } from "vitest";
import { z } from "zod";
import { readEvidenceBundle } from "../../../src/application/EvidenceBundleFiles.js";
import { toolContract } from "../../../src/contracts/toolContracts.js";
import { evidenceSchema } from "../../../src/domain/evidence.js";
import { pythonPycSchema } from "../../../src/domain/python/pythonPyc.js";
import { digestCanonicalValue } from "../../../src/domain/canonicalDigest.js";
import { analysisViewResultSchema } from "../../../src/domain/analysisView/analysisView.js";
import {
marshalCode,
pythonPycHeader,
} from "../../../src/python/PythonPyc.fixture.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { cliTest, type SharedMcpCall } from "../../support/cli/cliFixture.js";
const pycContract = toolContract("inspect_python_pyc");
const viewContract = toolContract("inspect_analysis_view");
const writeSameNamePyc = async (path: string): Promise<void> => {
await writeFile(
path,
Buffer.concat([
pythonPycHeader(3531),
marshalCode("py311", {
consts: [
marshalCode("py311", {
name: "same",
qualname: "First.same",
firstlineno: 11,
}),
marshalCode("py311", {
name: "same",
qualname: "Second.same",
firstlineno: 22,
}),
],
}),
]),
);
};
const assertSparseSelectors = async (
call: SharedMcpCall,
source: { readonly kind: "retained-evidence"; readonly evidence_id: string },
): Promise<void> => {
for (const [selector, items] of [
[{ indices: [2], fields: [] }, [{ source_index: 2 }]],
[{ names: [], fields: [] }, []],
[{ names: ["missing"], fields: [] }, []],
[{ indices: [], fields: [] }, []],
[{ names: ["same"], indices: [0], fields: [] }, []],
[
{ indices: [0], fields: ["nested_code"] },
[{ source_index: 0, nested_code: [1, 2] }],
],
] as const) {
const result = await call("inspect_analysis_view", {
source,
view: { kind: "python-pyc", collection: "code_objects", ...selector },
});
expect(result.isError).not.toBe(true);
expect(
viewContract.outputSchema.parse(result.structuredContent)
.normalized_result,
).toHaveProperty("items", items);
}
};
cliTest(
"queries same-name pyc objects through CLI/MCP after deleting the source",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-pyc-views-");
const path = join(root, "module.pyc");
await writeSameNamePyc(path);
const run = cli.run.bind(cli);
const complete = await run({
arguments: ["inspect-python-pyc", path, "--json"],
});
expect(complete.exitCode, complete.stderr).toBe(0);
const parent = pycContract.outputSchema.parse(complete.json);
const completeReport = pythonPycSchema.parse(parent.normalized_result);
const bundle = join(root, "complete.bundle.json");
const summarized = await run({
arguments: [
"inspect-python-pyc",
path,
"--detail",
"summary",
"--evidence_output",
bundle,
"--json",
],
});
expect(summarized.exitCode, summarized.stderr).toBe(0);
const delivered = z
.object({ summary: evidenceSchema })
.parse(summarized.json).summary;
expect(delivered.normalized_result).toMatchObject({
parent_evidence_id: parent.evidence_id,
summary: {
header: completeReport.header,
coverage: { status: "complete", code_objects: 3 },
},
});
expect(delivered.normalized_result).not.toHaveProperty(
"summary.code_objects",
);
const loaded = await readEvidenceBundle(bundle);
if (!loaded.ok) throw loaded.error;
expect(loaded.value.records).toEqual([parent]);
const call = await cli.sharedMcpCall?.();
if (call === undefined)
throw new Error("Expected shared stdio MCP session");
const response = await call("inspect_python_pyc", {
path,
detail: "summary",
});
expect(response.isError).not.toBe(true);
expect(
pycContract.outputSchema.parse(response.structuredContent)
.normalized_result,
).toEqual(delivered.normalized_result);
const view = {
kind: "python-pyc",
collection: "code_objects",
names: ["same"],
fields: ["name", "qualname", "nested_code"],
offset: 0,
limit: 1,
};
const directBundle = join(root, "selected.bundle.json");
const directCli = await run({
arguments: [
"inspect-python-pyc",
path,
"--detail",
"summary",
"--view",
JSON.stringify(view),
"--evidence_output",
directBundle,
"--json",
],
});
expect(directCli.exitCode, directCli.stderr).toBe(0);
const directCliEvidence = z
.object({ summary: evidenceSchema })
.parse(directCli.json).summary;
const direct = await call("inspect_python_pyc", {
path,
detail: "summary",
view,
});
expect(direct.isError).not.toBe(true);
const directEvidence = pycContract.outputSchema.parse(
direct.structuredContent,
);
expect(directEvidence.normalized_result).toEqual(
directCliEvidence.normalized_result,
);
const directSaved = await readEvidenceBundle(directBundle);
if (!directSaved.ok) throw directSaved.error;
expect(directSaved.value.records).toEqual([parent]);
await rm(path);
const source = {
kind: "retained-evidence" as const,
evidence_id: parent.evidence_id,
};
const first = await call("inspect_analysis_view", { source, view });
expect(first.isError).not.toBe(true);
const firstPage = viewContract.outputSchema.parse(first.structuredContent);
expect(firstPage.normalized_result).toEqual(
directEvidence.normalized_result,
);
expect(firstPage.evidence_links).toContain(parent.evidence_id);
expect(firstPage.normalized_result).toMatchObject({
items: [
{
source_index: 1,
name: "same",
qualname: "First.same",
nested_code: [],
},
],
coverage: { examined: 1, total: 2, next_offset: 1, exhausted: false },
pyc: { coverage: { status: "complete", code_objects: 3 } },
});
const request = { source, view: { ...view, offset: 1 } };
const second = await call("inspect_analysis_view", request);
expect(second.isError).not.toBe(true);
const page = viewContract.outputSchema.parse(second.structuredContent);
const projected = analysisViewResultSchema.parse(page.normalized_result);
expect(projected).toHaveProperty("items", [
{
source_index: 2,
name: "same",
qualname: "Second.same",
nested_code: [],
},
]);
const { view_digest, ...content } = projected;
expect(view_digest).toBe(digestCanonicalValue(content, "Analysis view"));
const offline = await run({
arguments: [
"inspect-analysis-view",
JSON.stringify(request),
"--evidence-bundle",
bundle,
"--json",
],
});
expect(offline.exitCode, offline.stderr).toBe(0);
expect(viewContract.outputSchema.parse(offline.json)).toEqual(page);
await assertSparseSelectors(call, source);
},
);
cliTest(
"rejects invalid pyc delivery before reading the target",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-pyc-invalid-delivery-");
const output = join(root, "unused.json");
const run = cli.run.bind(cli);
const view = JSON.stringify({
kind: "python-pyc",
collection: "code_objects",
});
for (const [flags, key] of [
[["--detail", "summary"], "evidence_output"],
[
["--detail", "complete", "--view", view, "--evidence_output", output],
"view",
],
[
["--detail", "summary", "--view", "{", "--evidence_output", output],
"view",
],
] as const) {
const result = await run({
arguments: [
"inspect-python-pyc",
"/rea-missing/module.pyc",
...flags,
"--json",
],
});
expect(result.exitCode).toBe(1);
expect(result.json).toMatchObject({
code: "invalid_request",
details: { issues: [{ path: [key] }] },
});
}
},
);