perf(test): reuse CLI boundary worker module graphs

Share CLI boundary module evaluation in bounded forks while preserving fresh command instances and child processes. Keep module-mocked cleanup tests and source/compiled product catalog verification isolated, and update focused artifact selection.

Flameox full cohort with V8 coverage: 102.8s to 96.6s; 290 passed and two existing skips. Statement, function and branch coverage maps and hit sets match across all 1,153 source files. After syncing main, 75 focused tests, typecheck, lint, docs checks and formatting pass; all 834 test files are discovered exactly once.
This commit is contained in:
morluto
2026-10-11 20:29:12 +08:00
parent 30787297d4
commit f178bf1c00
6 changed files with 48 additions and 26 deletions
@@ -1,302 +0,0 @@
import { Cli } from "incur";
import { expect, it, vi } from "vitest";
import type { BrowserScenarioCapturePort } from "../../../src/application/BrowserScenarioCapturePort.js";
import { createBrowserScenarioEvidence } from "../../../src/application/BrowserScenarioEvidence.js";
import type { BrowserScenarioSessionPort } from "../../../src/browser/BrowserScenarioSessionPort.js";
import { PlaywrightBrowserScenarioProvider } from "../../../src/browser/PlaywrightBrowserScenarioProvider.js";
import { PlaywrightScenarioBrowserCleanupOwner } from "../../../src/browser/PlaywrightScenarioBrowser.js";
import { registerBrowserScenarioCommands } from "../../../src/cliBrowserScenarioCommands.js";
import { sanitizeBrowserUrl } from "../../../src/domain/browserObservation.js";
import {
browserScenarioSchema,
type BrowserScenario,
} from "../../../src/domain/browserScenario.js";
import type { BrowserScenarioAction } from "../../../src/domain/browserScenarioValues.js";
import { browserStepArtifactsSchema } from "../../../src/domain/browserScenarioCaptureValues.js";
import { silentLogger } from "../../../src/logger.js";
import {
AnalysisCancelledError,
AnalysisTimeoutError,
} from "../../../src/domain/analysisErrorCore.js";
import { BrowserObservationError } from "../../../src/domain/browserObservationError.js";
import { parseEvidence } from "../../../src/domain/evidence.js";
import { jsonObjectSchema } from "../../../src/domain/jsonValue.js";
import { ok } from "../../../src/domain/result.js";
const state = vi.hoisted(() => ({
provider: undefined as BrowserScenarioCapturePort | undefined,
}));
vi.mock("../../../src/composition/browserScenario.js", () => ({
createBrowserScenarioProvider: () => state.provider,
}));
const scenario = browserScenarioSchema.parse({
browser: { mode: "launch", executable_path: "/fixture/chromium" },
start_url: { url: "https://app.example.test/" },
actions: [{ step_id: "wait", action: "wait_for_timeout", duration_ms: 1 }],
storage: {},
capture: { after_each_step: ["url"], at_end: [], events: [] },
});
// Controlled session failures exercise the real provider and cleanup owner;
// this fixture opens no browser process or profile directory.
class RetrySession implements BrowserScenarioSessionPort {
readonly mode = "launch";
readonly processOwnership = "provider-owned";
readonly product = "Fixture Chromium";
readonly version = "1";
readonly initialUrl = "https://app.example.test/";
closeBrowserCalls = 0;
profileRemovalCalls = 0;
readonly cleanup = new PlaywrightScenarioBrowserCleanupOwner({
closeBrowser: async () => {
this.closeBrowserCalls += 1;
if (this.closeBrowserCalls <= this.closeFailures)
throw new Error(`injected close failure ${this.closeBrowserCalls}`);
},
removeProfile: async () => {
expect(this.cleanup.browserClosed).toBe(true);
this.profileRemovalCalls += 1;
},
});
constructor(private readonly closeFailures = 1) {}
currentUrl() {
return this.initialUrl;
}
sanitizeUrl(value: string) {
return sanitizeBrowserUrl(value);
}
setStep(_index: number) {}
nextEventSequence() {
return 1;
}
lastEventSequence() {
return 0;
}
events() {
return { retained: 0, dropped: 0, items: [] };
}
async perform(_action: BrowserScenarioAction) {}
async capture(
requested: ReadonlySet<
BrowserScenario["capture"]["after_each_step"][number]
>,
) {
const artifact = (
kind: BrowserScenario["capture"]["after_each_step"][number],
) =>
!requested.has(kind)
? { state: "not_requested" }
: kind === "url"
? { state: "captured", value: this.sanitizeUrl(this.initialUrl) }
: { state: "missing", reason: "fixture unavailable" };
return browserStepArtifactsSchema.parse({
screenshot: artifact("screenshot"),
dom: artifact("dom"),
accessibility: artifact("accessibility"),
url: artifact("url"),
history: artifact("history"),
storage: artifact("storage"),
});
}
async close() {
await this.cleanup.close();
return "terminated-owned-process" as const;
}
redactError(error: unknown) {
return error instanceof Error ? error.message : "fixture failure";
}
}
const serveScenario = async () => {
const cli = Cli.create("browser-cleanup-test", { sync: false });
registerBrowserScenarioCommands(cli, silentLogger, {});
let stdout = "";
let exitCode = 0;
await cli.serve(
["capture-browser-scenario", JSON.stringify(scenario), "--json"],
{
env: {},
exit: (code) => {
exitCode = code;
},
stdout: (text) => {
stdout += text;
},
},
);
return {
output: jsonObjectSchema.parse(JSON.parse(stdout)),
exitCode,
processExitCode: process.exitCode,
};
};
it("retries retained browser cleanup before the one-shot CLI releases its provider", async () => {
const savedExitCode = process.exitCode;
const session = new RetrySession();
const provider = new PlaywrightBrowserScenarioProvider(async () => session);
const close = vi.spyOn(provider, "close");
state.provider = provider;
try {
const result = await serveScenario();
expect(result.processExitCode).toBe(1);
expect(result.output).toMatchObject({
code: "cleanup_incomplete",
category: "execution_failure",
details: {
cleanup: "incomplete",
resources: ["browser_transport", "browser_profile"],
partial_observation: {
capture: { browser: { cleanup: "incomplete" } },
},
},
});
const details = jsonObjectSchema.parse(result.output.details);
const partial = jsonObjectSchema.parse(details.partial_observation);
expect(jsonObjectSchema.parse(partial.capture).steps).toHaveLength(2);
expect(close).toHaveBeenCalledTimes(1);
expect(session.closeBrowserCalls).toBe(2);
expect(session.profileRemovalCalls).toBe(1);
} finally {
// The red baseline must also release this controlled owner.
await provider.close();
state.provider = undefined;
process.exitCode = savedExitCode;
}
});
it("preserves the initial partial observation when the provider cleanup retry also fails", async () => {
const savedExitCode = process.exitCode;
const session = new RetrySession(2);
const provider = new PlaywrightBrowserScenarioProvider(async () => session);
const close = vi.spyOn(provider, "close");
state.provider = provider;
try {
const result = await serveScenario();
expect(result.output).toMatchObject({ code: "cleanup_incomplete" });
expect(JSON.stringify(result.output)).toContain("injected close failure 1");
expect(JSON.stringify(result.output)).not.toContain(
"injected close failure 2",
);
expect(close).toHaveBeenCalledTimes(1);
expect(session.closeBrowserCalls).toBe(2);
expect(session.profileRemovalCalls).toBe(0);
// Retained ownership remains retryable after the command's failed retry.
await provider.close();
expect(session.closeBrowserCalls).toBe(3);
expect(session.profileRemovalCalls).toBe(1);
} finally {
await provider.close();
state.provider = undefined;
process.exitCode = savedExitCode;
}
});
it("retains completed Evidence when provider shutdown fails after a successful capture", async () => {
const savedExitCode = process.exitCode;
const provider = new PlaywrightBrowserScenarioProvider(
async () => new RetrySession(0),
);
const captured = await provider.captureScenario(scenario);
if (!captured.ok) throw captured.error;
const evidence = createBrowserScenarioEvidence(
scenario,
captured.value,
provider.identity(),
);
const close = vi.fn().mockRejectedValue(
new BrowserObservationError("capture_browser_scenario", "cleanup_failed", {
cleanup: {
reason: "injected shutdown failure",
resources: ["browser_profile"],
},
}),
);
state.provider = {
identity: () => provider.identity(),
captureScenario: async () => ok(captured.value),
close,
};
try {
const result = await serveScenario();
expect(result.processExitCode).toBe(1);
expect(result.output).toMatchObject({
code: "cleanup_incomplete",
details: { resources: ["browser_profile"] },
});
const details = jsonObjectSchema.parse(result.output.details);
expect(parseEvidence(details.partial_observation)).toEqual(evidence);
expect(close).toHaveBeenCalledTimes(1);
} finally {
await provider.close();
state.provider = undefined;
process.exitCode = savedExitCode;
}
});
it("preserves cancellation diagnostics while retrying retained cleanup", async () => {
const savedExitCode = process.exitCode;
const session = new RetrySession();
vi.spyOn(session, "capture").mockRejectedValue(
new AnalysisCancelledError("capture_browser_scenario"),
);
const provider = new PlaywrightBrowserScenarioProvider(async () => session);
state.provider = provider;
try {
const result = await serveScenario();
expect(result.output).toMatchObject({
code: "cleanup_incomplete",
category: "execution_failure",
details: {
cleanup: "incomplete",
diagnostics: {
primary_error: { code: "cancelled", category: "cancelled" },
},
partial_observation: { kind: "browser-scenario-observation" },
},
});
expect(session.closeBrowserCalls).toBe(2);
expect(session.profileRemovalCalls).toBe(1);
} finally {
await provider.close();
state.provider = undefined;
process.exitCode = savedExitCode;
}
});
it("preserves a thrown capture error when provider shutdown also rejects", async () => {
const savedExitCode = process.exitCode;
const provider = new PlaywrightBrowserScenarioProvider(
async () => new RetrySession(0),
);
const primary = new AnalysisTimeoutError("capture_browser_scenario", 123);
const close = vi
.fn()
.mockRejectedValue(new Error("secondary shutdown failure"));
state.provider = {
identity: () => provider.identity(),
captureScenario: async () => {
throw primary;
},
close,
};
try {
const result = await serveScenario();
expect(result.output).toMatchObject({
code: "provider_timeout",
category: "timeout",
});
expect(JSON.stringify(result.output)).not.toContain(
"secondary shutdown failure",
);
expect(close).toHaveBeenCalledTimes(1);
} finally {
await provider.close();
state.provider = undefined;
process.exitCode = savedExitCode;
}
});
-276
View File
@@ -1,276 +0,0 @@
import { copyFile, mkdir, readFile, rm, writeFile } from "node:fs/promises";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { afterEach, describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { SUPPORTED_CLIENT_DEFINITIONS } from "../../../src/application/SupportedClients.js";
import { CLI_COMMAND_NAMES } from "../../../src/cliCommandNames.js";
import { createCli } from "../../../src/cli.js";
import { TOOL_CONTRACTS } from "../../../src/contracts/toolContracts.js";
import {
HOPPER_OPERATIONS,
HOPPER_PROVIDER_IDENTITY,
} from "../../../src/hopper/HopperProviderCapabilities.js";
import {
GHIDRA_PROVIDER_IDENTITY,
GHIDRA_OPERATIONS,
} from "../../../src/ghidra/GhidraProviderCapabilities.js";
import {
documentationFactIssues,
skillReferenceIssues,
} from "../../../scripts/lib/docs-facts.mjs";
import { ensureGeneratedFile } from "../../../scripts/lib/generated-file.mjs";
import {
createCliInventory,
cliCommandDescriptionIssues,
cliCommandOptionNames,
} from "../../../scripts/lib/catalog-cli.mjs";
import {
createProductCatalog,
serializeProductCatalog,
} from "../../../scripts/lib/product-catalog.mjs";
const root = fileURLToPath(new URL("../../..", import.meta.url));
const temporaryRoots: string[] = [];
afterEach(async () => {
await Promise.all(
temporaryRoots
.splice(0)
.map((path) => rm(path, { recursive: true, force: true })),
);
});
describe("canonical product catalog", () => {
it("admits every documented browser scenario through the named contract", async () => {
const guide = await readFile(
join(root, "docs/browser-scenario-contract.md"),
"utf8",
);
const examples = [
...guide.matchAll(/```json\r?\n([\s\S]*?)\r?\n```/gu),
].map((match) => match[1] ?? "");
expect(examples.length).toBeGreaterThanOrEqual(2);
const contract = TOOL_CONTRACTS.find(
({ name }) => name === "capture_browser_scenario",
);
if (contract === undefined)
throw new Error("Missing browser scenario contract");
for (const example of examples)
expect(contract.inputSchema.safeParse(JSON.parse(example)).success).toBe(
true,
);
});
it("matches every source-derived build-generated product fact", async () => {
const catalog = await createProductCatalog(root);
expect(catalog.setup_clients.map(({ id }) => id)).toEqual(
SUPPORTED_CLIENT_DEFINITIONS.map(({ name }) => name),
);
expect(
catalog.providers.find(({ id }) => id === HOPPER_PROVIDER_IDENTITY.id)
?.capabilities,
).toEqual([...HOPPER_OPERATIONS].sort());
expect(
catalog.providers.find(({ id }) => id === GHIDRA_PROVIDER_IDENTITY.id)
?.capabilities,
).toEqual([...GHIDRA_OPERATIONS].sort());
expect(
JSON.parse(await readFile("docs/public/product-catalog.json", "utf8")),
).toEqual(catalog);
expect(await serializeProductCatalog(catalog)).toBe(
await readFile("docs/public/product-catalog.json", "utf8"),
);
await expect(documentationFactIssues(root, catalog)).resolves.toEqual([]);
}, 60_000);
});
describe("canonical CLI catalog", () => {
it("uses the same primary command names as the actual Incur router", () => {
const inventory = createCliInventory(createCli());
expect(inventory.primary).toEqual([...CLI_COMMAND_NAMES].sort());
expect(inventory.aliases).toEqual([
{ name: "compare-bundles", target: "compare" },
]);
}, 30_000);
it("describes every primary command argument and option", () => {
expect(cliCommandDescriptionIssues(createCli())).toEqual([]);
});
it("exposes the shared provider selector on every deep-analysis command", () => {
const cli = createCli();
for (const name of [
"analyze",
"inspect",
"decompile",
"xrefs",
"trace",
"function",
"annotate-native-function",
"inspect-native-api",
"search",
]) {
expect(cliCommandOptionNames(cli, name)).toContain("provider");
}
});
it("does not impose a private result limit on feature tracing", () => {
expect(cliCommandOptionNames(createCli(), "trace")).not.toContain("limit");
});
});
describe("canonical product catalog drift", () => {
it("rejects missing and repository-only links in an independently installed skill", async () => {
const directory = await createTestTempDirectory("rea-skill-references-");
const bundle = join(directory, "skill");
await mkdir(bundle);
await writeFile(join(directory, "repo-only.md"), "Repository-only guide");
await writeFile(join(bundle, "local.md"), "Bundled guide");
await writeFile(
join(bundle, "SKILL.md"),
[
"[bundled](local.md#guide)",
"[missing](missing.md)",
"[repository-only](../repo-only.md)",
"[public](https://example.test/guide)",
].join("\n"),
);
expect(await skillReferenceIssues(bundle)).toEqual([
"SKILL.md: missing skill reference: missing.md",
"SKILL.md: reference escapes installed skill bundle: ../repo-only.md",
]);
});
it("requires setup-client facts in the canonical installation guide", async () => {
const catalog = await createProductCatalog(root);
const drifted = {
...catalog,
setup_clients: [
...catalog.setup_clients,
{
id: "future_client",
display_name: "Future Client",
format: "json",
configuration: "managed",
},
],
};
const issues = await documentationFactIssues(root, drifted);
expect(issues).toContain("docs/installation.md: missing Future Client");
expect(issues).not.toContain("README.md: missing Future Client");
});
it("keeps translated readmes linked to canonical setup and tool details", async () => {
const directory = await createTestTempDirectory("rea-readme-facts-");
temporaryRoots.push(directory);
const paths = [
"README.md",
"README_zh.md",
"README_ja.md",
"README_ko.md",
"README_ar.md",
"website/locales/languages.json",
"docs/installation.md",
"AGENTS.md",
".github/pull_request_template.md",
];
for (const path of paths) {
const destination = join(directory, path);
await mkdir(dirname(destination), { recursive: true });
await copyFile(join(root, path), destination);
}
await mkdir(join(directory, "skills/reverse-engineer-anything"), {
recursive: true,
});
const translatedPath = join(directory, "README_zh.md");
const translated = await readFile(translatedPath, "utf8");
const catalog = await createProductCatalog(root);
await expect(documentationFactIssues(directory, catalog)).resolves.toEqual(
[],
);
for (const [original, changed] of [
[
"(docs/installation.md#supported-agents)",
"(docs/installation.md#missing-agents)",
],
[
"https://rea.tools/zh-CN/guides/native/",
"https://rea.tools/zh-CN/missing/",
],
[
"https://rea.tools/zh-CN/guides/native/",
"https://rea.tools/zh-TW/guides/native/",
],
[
"https://rea.tools/zh-CN/guides/native/",
"https://rea.tools/zh-CN/guides/native/?other=1",
],
] as const) {
expect(translated).toContain(original);
await writeFile(
translatedPath,
translated.replace(original, changed),
"utf8",
);
await expect(
documentationFactIssues(directory, catalog),
).resolves.toEqual([
"README_zh.md: documentation links differ from README.md",
]);
}
});
it("fails check mode without rewriting a stale generated artifact", async () => {
const directory = await createTestTempDirectory("rea-generated-check-");
temporaryRoots.push(directory);
const path = join(directory, "catalog.json");
await writeFile(path, "stale\n", "utf8");
await expect(
ensureGeneratedFile({
path,
source: "current\n",
check: true,
generateCommand: "npm run docs:generate",
}),
).rejects.toThrow("missing or stale");
expect(await readFile(path, "utf8")).toBe("stale\n");
await expect(
ensureGeneratedFile({
path,
source: "current\n",
check: false,
generateCommand: "npm run docs:generate",
}),
).resolves.toEqual({ changed: true });
expect(await readFile(path, "utf8")).toBe("current\n");
});
it("accepts and preserves native generated-file line endings", async () => {
const directory = await createTestTempDirectory("rea-generated-eol-");
temporaryRoots.push(directory);
const path = join(directory, "catalog.json");
await writeFile(path, "current\r\n", "utf8");
await expect(
ensureGeneratedFile({
path,
source: "current\n",
check: true,
generateCommand: "npm run docs:generate",
}),
).resolves.toEqual({ changed: false });
expect(await readFile(path, "utf8")).toBe("current\r\n");
await expect(
ensureGeneratedFile({
path,
source: "updated\n",
check: false,
generateCommand: "npm run docs:generate",
}),
).resolves.toEqual({ changed: true });
expect(await readFile(path, "utf8")).toBe("updated\r\n");
});
});