feat(electron): add autonomous Electron runtime analysis (#464)

* feat: add autonomous Electron runtime analysis

* feat(electron): add lifecycle and boundary telemetry

* feat(electron): capture runtime boundary evidence

* fix(electron): package boundary hook helper

* feat(electron): report active capture coverage

* fix(electron): account for bring-your-own runtime

* feat(electron): expand agent-owned runtime scenarios

* fix(ghidra): keep fixture credentials out of argv

* perf(test): serialize local test and docs workloads

* fix(electron): harden active runtime capture

* fix(inspector): require exact runtime target authorization

* fix(docs): make managed manifest host independent

* fix(ci): make generated catalog portable

* fix: unblock autonomous command and electron flows

* fix(electron): close popup and detached helper gaps
This commit is contained in:
morluto
2026-08-05 19:07:46 +08:00
committed by GitHub
parent 51559245d2
commit 8f229ede70
104 changed files with 5055 additions and 196 deletions
@@ -80,6 +80,18 @@ describe("package installation workflows", () => {
expect(release).not.toContain('npm run verify:published -- "${version}"');
expect(canary).toContain('mkdtemp(join(tmpdir(), "rea-published-canary-")');
expect(canary).toContain("cwd: canaryRoot");
expect(release).toContain("publish-mcp:");
expect(release).toContain("needs: [release-please, publish]");
expect(release).toContain("MCP_PUBLISHER_VERSION: v1.8.0");
expect(release).toContain("mcp-publisher validate");
expect(release).toContain("mcp-publisher login github-oidc");
expect(release).toContain("mcp-publisher publish");
expect(release).toContain("id-token: write");
expect(release).toContain("contents: read");
expect(release).not.toContain("MCP_GITHUB_TOKEN");
expect(release.indexOf("publish-mcp:")).toBeGreaterThan(
release.indexOf("npm publish --access public"),
);
});
it("uses direct Node ownership on macOS and Windows", () => {
@@ -0,0 +1,135 @@
import { expect, it } from "vitest";
import { electronActiveObservationInputSchema } from "../../../src/domain/electronActiveObservation.js";
import { runElectronActions } from "../../../src/browser/PlaywrightElectronActiveActions.js";
it("parses bounded window, renderer, and deep-link actions for agents", () => {
const input = electronActiveObservationInputSchema.parse({
schema_version: 1,
executable_path: "/opt/electron",
application_path: "/opt/app/main.js",
application_root: "/opt/app",
actions: [
{ step_id: "first-window", kind: "click", selector: "#run" },
{ step_id: "second-window", kind: "renderer-reload", window_index: 1 },
{ step_id: "restart", kind: "renderer-crash", window_index: 1 },
{
step_id: "deep-link",
kind: "deep-link",
delivery: "second-instance",
url: "rea-fixture://open/item",
},
],
approved: true,
});
expect(input.actions).toEqual([
{
step_id: "first-window",
kind: "click",
selector: "#run",
window_index: 0,
},
{ step_id: "second-window", kind: "renderer-reload", window_index: 1 },
{ step_id: "restart", kind: "renderer-crash", window_index: 1 },
{
step_id: "deep-link",
kind: "deep-link",
delivery: "second-instance",
url: "rea-fixture://open/item",
},
]);
});
it("rejects non-absolute deep-link values", () => {
const result = electronActiveObservationInputSchema.safeParse({
schema_version: 1,
executable_path: "/opt/electron",
application_path: "/opt/app/main.js",
application_root: "/opt/app",
actions: [
{
step_id: "bad-link",
kind: "deep-link",
delivery: "open-url",
url: "not a URL",
},
],
approved: true,
});
expect(result.success).toBe(false);
});
it("redacts action inputs from Playwright failures", async () => {
const selector = "#secret-selector";
const input = electronActiveObservationInputSchema.parse({
schema_version: 1,
executable_path: "/opt/electron",
application_path: "/opt/app/main.js",
application_root: "/opt/app",
actions: [{ step_id: "click-step", kind: "click", selector }],
approved: true,
});
const page = {
locator: () => ({
click: async () => {
throw new Error(`locator ${selector} failed with token=raw-secret`);
},
}),
};
const application = {
windows: () => [page],
};
const result = await runElectronActions(
application as never,
input,
{},
Date.now() + 1_000,
);
expect(result[0]).toMatchObject({
status: "failed",
error: "locator <redacted-input> failed with token=[REDACTED]",
});
expect(result[0]?.error).not.toContain(selector);
expect(result[0]?.error).not.toContain("raw-secret");
});
it("runs an untargeted deep-link without requiring a BrowserWindow", async () => {
const input = electronActiveObservationInputSchema.parse({
schema_version: 1,
executable_path: "/opt/electron",
application_path: "/opt/app/main.js",
application_root: "/opt/app",
actions: [
{
step_id: "open-deep-link",
kind: "deep-link",
delivery: "second-instance",
url: "rea-fixture://open/item",
},
],
approved: true,
});
const application = {
windows: () => [],
evaluate: async () => true,
};
const result = await runElectronActions(
application as never,
input,
{},
Date.now() + 1_000,
);
expect(result).toMatchObject([
{
step_id: "open-deep-link",
status: "completed",
error: null,
},
]);
});
@@ -0,0 +1,242 @@
import { rm, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { spawn } from "node:child_process";
import { afterEach, expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
const temporary: string[] = [];
afterEach(async () => {
await Promise.all(
temporary
.splice(0)
.map(async (path) => rm(path, { force: true, recursive: true })),
);
});
it("keeps active hook lifecycle and IPC evidence bounded at the process boundary", async () => {
const root = await createTestTempDirectory("rea-electron-hook-");
temporary.push(root);
await writeFile(
join(root, "electron.js"),
`const { EventEmitter } = require("node:events");
const app = new EventEmitter();
app.relaunch = () => undefined;
app.setAsDefaultProtocolClient = () => true;
app.setLoginItemSettings = () => undefined;
const ipcMain = new EventEmitter();
ipcMain.handlers = new Map();
ipcMain.handle = (channel, listener) => ipcMain.handlers.set(channel, listener);
const ipcRenderer = {
send: () => undefined,
sendSync: () => "ok",
invoke: () => Promise.resolve("ok"),
postMessage: () => undefined,
};
class WebContents extends EventEmitter {
constructor() {
super();
this.id = 12;
}
loadFile() { return Promise.resolve(); }
loadURL() { return Promise.resolve(); }
loadDataURL() { return Promise.resolve(); }
send() { return undefined; }
postMessage() { return undefined; }
setWindowOpenHandler(handler) { this.windowOpenHandler = handler; return undefined; }
}
class BrowserWindow extends EventEmitter {
constructor(options) {
super();
this.id = 3;
this.webContents = new WebContents();
this.options = options;
}
}
const utilityProcess = {
fork: () => {
const child = new EventEmitter();
child.pid = 44;
child.postMessage = () => undefined;
return child;
},
};
const shell = { openExternal: () => Promise.resolve(), openPath: () => Promise.resolve() };
const createSession = () => {
const value = new EventEmitter();
value.setPermissionRequestHandler = () => undefined;
value.setPermissionCheckHandler = () => undefined;
value.setCertificateVerifyProc = () => undefined;
return value;
};
const session = createSession();
const customSession = createSession();
const contextBridge = {
exposeInMainWorld: () => undefined,
exposeInIsolatedWorld: () => undefined,
};
module.exports = {
app,
BrowserWindow,
contextBridge,
ipcMain,
ipcRenderer,
session: {
defaultSession: session,
fromPartition: () => customSession,
},
shell,
utilityProcess,
};
`,
);
const script = join(root, "exercise.cjs");
await writeFile(
script,
`(async () => {
const electron = require("electron");
const window = new electron.BrowserWindow({ webPreferences: { preload: "/approved/preload.js" } });
const channel = "x".repeat(2048);
electron.ipcMain.handle(channel, async () => ({ ok: true }));
await electron.ipcMain.handlers.get(channel)({ sender: { id: 9 }, senderFrame: { routingId: 7 } }, ...Array.from({ length: 40 }, () => ({ value: true })));
window.webContents.send("main-to-renderer", { value: true });
window.webContents.emit("render-process-gone", { reason: "crashed" });
const utility = electron.utilityProcess.fork("utility.js");
utility.emit("message", { data: { value: true } });
utility.postMessage({ value: true });
electron.session.defaultSession.emit("will-download", window.webContents, { cancel() {} });
electron.session.fromPartition("persist:custom").emit("will-download", window.webContents, { cancel() {} });
const defaultPopupDecision = window.webContents.windowOpenHandler({ url: "https://default-popup.invalid" });
window.webContents.setWindowOpenHandler(() => ({ action: "allow" }));
const popupDecision = window.webContents.windowOpenHandler({ url: "https://popup.invalid" });
electron.shell.openExternal("https://example.invalid").catch(() => undefined);
electron.app.relaunch();
electron.contextBridge.exposeInMainWorld("api", { value: true });
window.webContents.loadURL("https://example.invalid").catch(() => undefined);
try { process.dlopen({}, "/missing/native.node"); } catch {}
process.stdout.write(JSON.stringify({ snapshot: globalThis.__reaElectronActiveSnapshot(), default_popup_decision: defaultPopupDecision, popup_decision: popupDecision }) + "\\n");
})();
`,
);
const hook = join(process.cwd(), "scripts/electron-active-hook.cjs");
const output = await runNode(hook, script, root, root);
const result = JSON.parse(output.trim().split("\n").at(-1) ?? "null") as {
readonly default_popup_decision: { readonly action: string };
readonly popup_decision: { readonly action: string };
readonly snapshot: {
readonly hook_error: boolean;
readonly events: readonly Record<string, unknown>[];
};
};
const { snapshot } = result;
expect(snapshot.hook_error).toBe(false);
expect(snapshot.events).toEqual(
expect.arrayContaining([
expect.objectContaining({ kind: "window-lifecycle", event: "created" }),
expect.objectContaining({ kind: "preload", event: "configured" }),
expect.objectContaining({ kind: "shell-attempt", phase: "blocked" }),
expect.objectContaining({ kind: "updater", phase: "blocked" }),
expect.objectContaining({ kind: "native-addon" }),
expect.objectContaining({ kind: "popup-attempt", phase: "blocked" }),
]),
);
expect(result.default_popup_decision).toEqual({ action: "deny" });
expect(result.popup_decision).toEqual({ action: "deny" });
expect(
snapshot.events.filter(
(event) => event.kind === "download" && event.phase === "blocked",
),
).toHaveLength(2);
const ipc = snapshot.events.find(
(event) => event.kind === "main-handler-invocation",
);
expect(ipc).toMatchObject({
correlation_id: expect.stringMatching(/^capture:\d+:\d+$/u),
channel_truncated: true,
argument_shapes_truncated: true,
direction: "renderer-to-main",
sender: "webContents:9",
frame: "frame:7",
});
expect(ipc?.channel).toHaveLength(1_024);
expect(ipc?.argument_shapes).toHaveLength(32);
});
it("preserves fatal process termination after recording uncaught exceptions", async () => {
const root = await createTestTempDirectory("rea-electron-hook-fatal-");
temporary.push(root);
const script = join(root, "fatal.cjs");
await writeFile(script, 'throw new Error("fatal-hook-secret");\n');
const hook = join(process.cwd(), "scripts/electron-active-hook.cjs");
const result = await runNodeStatus(hook, script, root, root);
expect(result.code).not.toBe(0);
expect(result.stderr).toContain("fatal-hook-secret");
});
const runNode = (
hook: string,
script: string,
moduleRoot: string,
cwd: string,
): Promise<string> =>
new Promise((resolve, reject) => {
const child = spawn(process.execPath, ["-r", hook, script], {
cwd,
env: {
...process.env,
NODE_PATH: moduleRoot,
REA_ELECTRON_ACTIVE_MAX_RUNTIME_EVENTS: "200",
},
stdio: ["ignore", "pipe", "pipe"],
});
const stdout: Buffer[] = [];
const stderr: Buffer[] = [];
child.stdout.on("data", (chunk: Buffer) => stdout.push(chunk));
child.stderr.on("data", (chunk: Buffer) => stderr.push(chunk));
child.once("error", reject);
child.once("close", (code) => {
if (code === 0) {
const text = Buffer.concat(stdout).toString("utf8");
if (text.length > 0) resolve(text);
else
reject(
new Error(
`hook fixture produced no output: ${Buffer.concat(stderr).toString("utf8")}`,
),
);
} else
reject(
new Error(
`hook fixture exited with ${String(code)}: ${Buffer.concat(stderr).toString("utf8")}`,
),
);
});
});
const runNodeStatus = (
hook: string,
script: string,
moduleRoot: string,
cwd: string,
): Promise<{ readonly code: number | null; readonly stderr: string }> =>
new Promise((resolve, reject) => {
const child = spawn(process.execPath, ["-r", hook, script], {
cwd,
env: {
...process.env,
NODE_PATH: moduleRoot,
REA_ELECTRON_ACTIVE_MAX_RUNTIME_EVENTS: "200",
},
stdio: ["ignore", "pipe", "pipe"],
});
const stderr: Buffer[] = [];
child.stderr.on("data", (chunk: Buffer) => stderr.push(chunk));
child.once("error", reject);
child.once("close", (code) =>
resolve({ code, stderr: Buffer.concat(stderr).toString("utf8") }),
);
});
@@ -93,6 +93,43 @@ describe("passive V8 Inspector provider", () => {
}
});
test("excludes an Electron main target that reports only bare file://", async () => {
const fixture = await runtimeFixture();
const fake = await startFakeV8Inspector({
targetUrl: "file://",
scriptUrls: [pathToFileURL(fixture.entry).href],
});
try {
const provider = new V8InspectorProvider();
const listed = await provider.listTargets({
inspector_endpoint: fake.endpoint,
allowed_file_roots: [fixture.root],
allowed_origins: [],
approved: true,
offset: 0,
limit: 100,
});
expect(listed.ok).toBe(true);
if (!listed.ok) return;
expect(listed.value.targets.total).toBe(0);
expect(listed.value.targets.items).toEqual([]);
const observed = await provider.observe(
observeInput(
fake.endpoint,
fake.targetId,
fixture.root,
"electron-main",
),
);
expect(observed.ok).toBe(false);
if (observed.ok) return;
expect(observed.error.message).toMatch(/outside_file_roots|target/u);
} finally {
await fake.close();
}
});
test.each([
["node", "node"],
["electron-main", "node"],
@@ -18,6 +18,7 @@ import {
} from "../../../src/application/InvestigationProviders.js";
import { CDP_BROWSER_PROVIDER_IDENTITY } from "../../../src/browser/CdpBrowserProvider.js";
import { CDP_ELECTRON_PROVIDER_IDENTITY } from "../../../src/browser/CdpElectronProvider.js";
import { PLAYWRIGHT_ELECTRON_ACTIVE_PROVIDER_IDENTITY } from "../../../src/browser/PlaywrightElectronActiveProvider.js";
import { PLAYWRIGHT_BROWSER_SCENARIO_PROVIDER_IDENTITY } from "../../../src/browser/PlaywrightBrowserScenarioProvider.js";
import { V8_INSPECTOR_PROVIDER_IDENTITY } from "../../../src/browser/V8InspectorProvider.js";
import { CLI_COMMAND_NAMES } from "../../../src/cliCommandNames.js";
@@ -81,6 +82,7 @@ describe("canonical product catalog", () => {
CDP_BROWSER_PROVIDER_IDENTITY,
PLAYWRIGHT_BROWSER_SCENARIO_PROVIDER_IDENTITY,
CDP_ELECTRON_PROVIDER_IDENTITY,
PLAYWRIGHT_ELECTRON_ACTIVE_PROVIDER_IDENTITY,
V8_INSPECTOR_PROVIDER_IDENTITY,
JAVASCRIPT_APPLICATION_PROVIDER,
JAVASCRIPT_RUNTIME_RECONCILIATION_PROVIDER,
@@ -102,6 +104,11 @@ describe("canonical product catalog", () => {
({ id }) => id === CDP_ELECTRON_PROVIDER_IDENTITY.id,
)?.capabilities,
).toEqual(["inspect_electron_page", "list_electron_targets"]);
expect(
catalog.providers.find(
({ id }) => id === PLAYWRIGHT_ELECTRON_ACTIVE_PROVIDER_IDENTITY.id,
)?.capabilities,
).toEqual(["capture_electron_scenario"]);
expect(
catalog.providers.find(
({ id }) => id === JAVASCRIPT_APPLICATION_PROVIDER.id,
+107 -2
View File
@@ -1,5 +1,5 @@
import { mkdir, rm, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { mkdir, rm, symlink, writeFile } from "node:fs/promises";
import { dirname, join } from "node:path";
import { pathToFileURL } from "node:url";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
@@ -10,6 +10,7 @@ import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { composeBinarySessionFromFactory } from "../../../src/application/BinarySessionComposition.js";
import type { BinarySession } from "../../../src/application/BinarySession.js";
import type { ElectronActiveObservationPort } from "../../../src/application/ElectronActiveObservationPort.js";
import { loadConfiguredPermissionAuthority } from "../../../src/application/PermissionConfiguration.js";
import { CdpElectronProvider } from "../../../src/browser/CdpElectronProvider.js";
import { parseConfig } from "../../../src/config.js";
@@ -20,6 +21,7 @@ import {
type FakeCdpBrowser,
} from "../../fixtures/fakeCdpBrowser.js";
import { writeElectronBoundaryFixture } from "../../fixtures/electronBoundaryApplication.js";
import { createElectronActiveObservationFixtureResult } from "../../fixtures/electronActiveObservationResult.js";
const browsers: FakeCdpBrowser[] = [];
const resources: Array<{ close(): Promise<unknown> }> = [];
@@ -183,6 +185,109 @@ it("exposes root-confined Electron discovery and inspection as Evidence v2", asy
expect(browser.commands).toHaveLength(commandsBeforeDenial);
}, 20_000);
it("exposes active Electron scenarios through the separately granted MCP boundary", async () => {
const root = await createTestTempDirectory("rea-electron-active-mcp-");
temporary.push(root);
const applicationPath = join(root, "main.js");
await writeFile(applicationPath, "module.exports = {};\n");
const aliasedRoot = join(root, "..", `${root.split("/").at(-1)}-alias`);
await symlink(root, aliasedRoot, "dir");
temporary.push(aliasedRoot);
const capturedInputs: unknown[] = [];
const activeResult =
createElectronActiveObservationFixtureResult(applicationPath);
const provider: ElectronActiveObservationPort = {
identity: () => ({
id: "test-electron-active",
name: "Test Electron active provider",
version: "1",
}),
capture: async (input) => {
capturedInputs.push(input);
return { ok: true, value: activeResult };
},
};
const config = parseConfig({
REA_ELECTRON_AUTOMATE_ENABLED: "true",
REA_ELECTRON_AUTOMATE_AUTO_GRANT: "true",
REA_ELECTRON_AUTOMATE_EXECUTABLE_ROOTS_JSON: JSON.stringify([
dirname(process.execPath),
]),
REA_ELECTRON_AUTOMATE_APPLICATION_ROOTS_JSON: JSON.stringify([root]),
});
if (!config.ok) throw config.error;
const authority = await loadConfiguredPermissionAuthority(config.value);
if (!authority.ok) throw authority.error;
const session = composeBinarySessionFromFactory(() => ({
execute: () => Promise.resolve(observed(null)),
close: () => Promise.resolve(),
}));
const server = createServer(session, session, {
electronActiveObservation: provider,
permissionAuthority: authority.value,
availabilityPolicy: () => ({
processCaptureEnabled: false,
evidenceFileRoots: 0,
investigationInputRoots: 0,
electronAutomationEnabled: true,
}),
});
const client = new Client({ name: "electron-active-mcp-test", version: "1" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
resources.push(client, server, session);
await server.connect(serverTransport);
await client.connect(clientTransport);
const captured = await client.callTool({
name: "capture_electron_scenario",
arguments: {
schema_version: 1,
executable_path: process.execPath,
application_path: join(aliasedRoot, "main.js"),
application_root: aliasedRoot,
args: ["--token", "super-secret"],
actions: [
{ step_id: "submit", kind: "click", selector: "#submit-secret" },
],
approved: true,
},
});
expect(captured.isError, JSON.stringify(captured)).not.toBe(true);
expect(captured.structuredContent).toMatchObject({
result: {
application: { process_ownership: "provider-owned" },
ipc: { events: [{ channel: "readiness:echo" }] },
coverage: {
status: "partial_attach",
pre_capture_activity: "unavailable",
},
},
});
expect(capturedInputs).toHaveLength(1);
expect(capturedInputs[0]).toMatchObject({
application_path: applicationPath,
application_root: root,
});
expect(JSON.stringify(captured.structuredContent)).not.toContain(
"submit-secret",
);
expect(JSON.stringify(captured.structuredContent)).not.toContain(
"super-secret",
);
const evidenceId = Reflect.get(
captured.structuredContent ?? {},
"evidence_id",
);
expect(session.evidenceById(String(evidenceId))).toMatchObject({
predicate_type: "rea.electron-active-scenario/v1",
parameters: {
args: ["--token", "<redacted>"],
actions: [{ step_id: "submit", kind: "click" }],
},
});
}, 20_000);
it("exposes the target-free static JavaScript application workflow", async () => {
const root = await createTestTempDirectory("rea-electron-static-mcp-");
temporary.push(root);
@@ -1,4 +1,5 @@
import { isInputRequiredResult } from "@modelcontextprotocol/server";
import { realpathSync } from "node:fs";
import { describe, expect, it } from "vitest";
import { PermissionAuthority } from "../../../src/application/PermissionAuthority.js";
import { createPermissionPolicy } from "../../../src/domain/permissionPolicy.js";
@@ -8,7 +9,7 @@ import {
} from "../../../src/server/ProcessCaptureElicitation.js";
const request = {
capability: "process_capture" as const,
roots: ["/tmp"],
roots: [realpathSync("/tmp")],
executables: [process.execPath],
environment_names: ["PATH"],
network: "external" as const,
@@ -1,4 +1,5 @@
import { isInputRequiredResult } from "@modelcontextprotocol/server";
import { realpathSync } from "node:fs";
import { describe, expect, it } from "vitest";
import { PermissionAuthority } from "../../../src/application/PermissionAuthority.js";
import { createPermissionPolicy } from "../../../src/domain/permissionPolicy.js";
@@ -8,7 +9,7 @@ import {
} from "../../../src/server/ProcessCaptureElicitation.js";
const request = {
capability: "process_capture" as const,
roots: ["/tmp"],
roots: [realpathSync("/tmp")],
executables: [process.execPath],
environment_names: ["PATH"],
network: "external" as const,
@@ -1,5 +1,6 @@
import { isInputRequiredResult } from "@modelcontextprotocol/server";
import { mkdir, rm } from "node:fs/promises";
import { realpathSync } from "node:fs";
import { describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { PermissionAuthority } from "../../../src/application/PermissionAuthority.js";
@@ -10,7 +11,7 @@ import {
} from "../../../src/server/ProcessCaptureElicitation.js";
const request = {
capability: "process_capture" as const,
roots: ["/tmp"],
roots: [realpathSync("/tmp")],
executables: [process.execPath],
environment_names: ["PATH"],
network: "external" as const,
+3 -3
View File
@@ -77,10 +77,10 @@ describe("server and catalog identity", () => {
expect(SDK_IDENTITY.server).toBe(
packageJson.dependencies["@modelcontextprotocol/server"],
);
expect(CLI_COMMAND_NAMES).toHaveLength(67);
expect(new Set(CLI_COMMAND_NAMES).size).toBe(67);
expect(CLI_COMMAND_NAMES).toHaveLength(68);
expect(new Set(CLI_COMMAND_NAMES).size).toBe(68);
expect(CATALOG_IDENTITY.counts).toEqual({
cli_commands: 67,
cli_commands: 68,
mcp_tools: TOOL_CONTRACTS.length,
mcp_prompts: 6,
mcp_resources: 2,
@@ -59,7 +59,7 @@ function collectionTriggers() {
parent_pid: 1,
command: "rea-reactive-worker",
process_group_id: 1,
session_id: 1,
session_id: process.platform === "darwin" ? null : 1,
},
["at_ms"],
),
@@ -2,6 +2,7 @@ import { describe, expect, it, vi } from "vitest";
import {
cleanupOwnedProcessGroup,
observeOwnedProcessLineage,
verifyNoTokenOwnedProcesses,
type ProcessOwnershipHost,
} from "../../../src/process/ProcessOwnership.js";
const ownership = {
@@ -34,6 +35,74 @@ const host = (
signalGroup,
};
};
describe("owned process-group cleanup discovery", () => {
it("signals token-owned groups that were reparented outside the launcher tree", async () => {
const signalGroup = vi.fn();
const adapter: ProcessOwnershipHost = {
listProcesses: () =>
Promise.resolve([
{
pid: 100,
parentPid: 1,
processGroupId: 100,
state: "S",
command: "fixture",
},
{
pid: 900,
parentPid: 1,
processGroupId: 900,
state: "S",
command: "detached-helper",
},
{
pid: 901,
parentPid: 900,
processGroupId: 900,
state: "S",
command: "detached-worker",
},
]),
environment: () => Promise.resolve({ REA_PROCESS_RUN_ID: "run-token" }),
signalGroup,
};
await expect(
cleanupOwnedProcessGroup(
{ ...ownership, sweepTokenOwnedProcesses: true },
adapter,
),
).resolves.toEqual({ cleaned: true, signaled: true });
expect(signalGroup.mock.calls.map(([groupId]) => groupId)).toEqual([
100, 900,
]);
});
it("fails closed when a token-owned process remains after cleanup", async () => {
const adapter: ProcessOwnershipHost = {
listProcesses: () =>
Promise.resolve([
{
pid: 900,
parentPid: 1,
processGroupId: 900,
state: "S",
command: "detached-helper",
},
]),
environment: () => Promise.resolve({ REA_PROCESS_RUN_ID: "run-token" }),
signalGroup: vi.fn(),
};
await expect(
verifyNoTokenOwnedProcesses("run-token", adapter),
).resolves.toEqual({
cleaned: false,
reason: "token-owned process remained after cleanup",
});
});
});
describe("owned process-group cleanup discovery", () => {
it("fails before signaling when any descendant-group member is unowned", async () => {
const signalGroup = vi.fn();
@@ -67,6 +67,15 @@ describe("provider process runtime and wait primitives", () => {
});
});
it("fails closed for a Windows runtime root without native DACL authority", async () => {
await expect(
PrivateRuntimeRoot.create({ platform: "win32" }),
).rejects.toMatchObject({
code: "private-runtime-root-authority-unavailable",
message: expect.stringContaining("chmod(0700)"),
});
});
it("clears the startup timer and external cancellation listener", async () => {
vi.useFakeTimers();
const controller = new AbortController();
@@ -335,6 +344,45 @@ describe("provider process spawning primitives", () => {
},
);
it.skipIf(process.platform === "win32")(
"stops a detached fixture descendant when its launcher receives SIGTERM",
async () => {
const launcher = spawnProviderProcessFixture("detached-child");
let detachedChildPid: number | undefined;
const cleanup = async (): Promise<void> => {
await stopProviderProcessFixture(launcher);
if (detachedChildPid === undefined) return;
try {
process.kill(detachedChildPid, "SIGKILL");
} catch (cause: unknown) {
if (
!(
cause instanceof Error &&
"code" in cause &&
cause.code === "ESRCH"
)
)
throw cause;
}
};
try {
detachedChildPid = await waitForDetachedProviderChild(launcher);
const launcherPid = launcher.pid;
if (launcherPid === undefined)
throw new Error("Detached fixture launcher did not expose a PID");
launcher.kill("SIGTERM");
await Promise.all([
waitForPidExit(launcherPid),
waitForPidExit(detachedChildPid),
]);
} catch (cause: unknown) {
await cleanup();
throw cause;
}
await cleanup();
},
);
it("allows interpreter launchers to rely on parent and run-token identity", async () => {
const spawned = await spawnOwnedProviderProcess({
command: process.execPath,
@@ -61,21 +61,22 @@ class FixtureLauncher implements GhidraLauncher {
this.tokens.push(session.token);
const projectRoot = join(session.runtimeRoot, "project");
await mkdir(projectRoot, { recursive: true });
const process_ = spawn(
process.execPath,
[
fixturePath,
session.endpointPath,
session.token,
session.runId,
session.providerVersion,
session.profileDigest,
session.targetSha256,
session.transport,
this.mode,
],
{ stdio: ["ignore", "pipe", "pipe"] },
);
const process_ = spawn(process.execPath, [fixturePath], {
stdio: ["ignore", "pipe", "pipe"],
env: {
...process.env,
REA_GHIDRA_FIXTURE_CONFIG: JSON.stringify({
endpointPath: session.endpointPath,
token: session.token,
runId: session.runId,
providerVersion: session.providerVersion,
profileDigest: session.profileDigest,
targetSha256: session.targetSha256,
transport: session.transport,
mode: this.mode,
}),
},
});
this.processes.push(process_);
return ok({
process: process_,
@@ -142,7 +142,7 @@ describe("Ghidra provider", () => {
});
describe("Ghidra platform support", () => {
it("admits only native x86-64 PE applications on Windows P0", () => {
it("keeps Windows P0 unavailable until native isolation authority exists", () => {
const ghidra = provider({ ...installationHost(), platform: "win32" });
const nativeApplication: BinaryTarget = {
...executableTarget("pe", "x86_64"),
@@ -158,12 +158,35 @@ describe("Ghidra platform support", () => {
managed: false,
},
});
expect(ghidra.inspectAvailability()).toMatchObject({
status: "unavailable",
code: "unsupported_host",
reason: expect.stringContaining("native authority is unavailable"),
diagnostics: {
windows_security: {
job_object_process_ownership: expect.objectContaining({
available: false,
proof: "not-proven",
}),
private_runtime_dacl: expect.objectContaining({
available: false,
proof: "not-proven",
}),
reparse_safe_path_admission: expect.objectContaining({
available: false,
proof: "not-proven",
}),
},
},
});
expect(ghidra.capabilities()).toEqual(
expect.arrayContaining([
expect.objectContaining({
operation: "list_procedures",
available: false,
availabilityCode: "unsupported_host",
limitations: expect.arrayContaining([
expect.stringContaining("bounded taskkill termination"),
expect.stringContaining("bounded taskkill cleanup"),
expect.stringContaining("private DACL enforcement"),
]),
}),
@@ -182,7 +182,7 @@ describe("Linux private display selection", () => {
);
it("reports missing helper dependencies without exposing raw stderr", () => {
for (const [option, reason] of [
for (const [option] of [
["--xauth", "missing_xauth"],
["--xvfb", "missing_xvfb"],
] as const) {
@@ -198,9 +198,10 @@ describe("Linux private display selection", () => {
value: {
status: "error",
failure_code: "runtime_dependency_unavailable",
reason,
},
});
if (parsed.ok)
expect(parsed.value.reason).toMatch(/^missing_(xauth|xvfb)$/u);
expect(result.stderr).not.toContain("Traceback");
}
});
@@ -51,6 +51,7 @@ describe("tool contract inventory", () => {
"inspect_electron_page",
"analyze_javascript_application",
"reconcile_javascript_runtime",
"capture_electron_scenario",
]);
expect(APPLICATION_TOOL_CONTRACTS.map(({ name }) => name)).toEqual([
"trace_application_feature",
@@ -6,11 +6,14 @@ import { afterEach, expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { createElectronEvidence } from "../../../src/application/ElectronEvidence.js";
import { createElectronActiveEvidence } from "../../../src/application/ElectronActiveEvidence.js";
import { analyzeJavaScriptApplication } from "../../../src/application/JavaScriptApplicationService.js";
import { reconcileJavaScriptRuntime } from "../../../src/domain/javascriptRuntimeReconciliation.js";
import { javascriptRuntimeReconciliationResultSchema } from "../../../src/domain/javascriptRuntimeReconciliationSchemas.js";
import { electronActiveObservationInputSchema } from "../../../src/domain/electronActiveObservation.js";
import { createWebTextArtifact } from "../../../src/domain/webContentArtifact.js";
import { permissionAuthorityForRoot } from "../../fixtures/permissionAuthority.js";
import { createElectronActiveObservationFixtureResult } from "../../fixtures/electronActiveObservationResult.js";
const SOURCE = `const worker = new Worker("./worker.js");\nexport const observed = worker;\n`;
@@ -142,6 +145,87 @@ it("keeps source-map declarations outside primary matching authority", async ()
});
});
it("reconciles active Electron as a partial target-only runtime capture", async () => {
const fixture = await applicationFixture();
temporary.push(fixture);
const staticEvidence = await analyzeFixture(fixture);
const applicationPath = join(fixture, "main.js");
const input = electronActiveObservationInputSchema.parse({
schema_version: 1,
executable_path: process.execPath,
application_path: applicationPath,
application_root: fixture,
actions: [],
approved: true,
});
const runtimeEvidence = createElectronActiveEvidence(
input,
createElectronActiveObservationFixtureResult(applicationPath),
{
id: "rea-playwright-electron-active",
name: "REA Playwright active Electron observation provider",
version: "1",
},
);
const result = reconcileJavaScriptRuntime({
static_layers: [{ role: "application", analysis: staticEvidence }],
runtime_observations: [runtimeEvidence],
});
expect(result.runtime_captures).toMatchObject([
{
kind: "electron-active",
scripts: 0,
frames: 0,
workers: 0,
scripts_complete_within_scope: false,
},
]);
expect(result.coverage.status).toBe("partial");
expect(result.limitations.join(" ")).toMatch(
/incomplete|not reported as executed/u,
);
});
it("hashes the retained Electron scenario projection, not raw selectors or secrets", async () => {
const fixture = await applicationFixture();
temporary.push(fixture);
const applicationPath = join(fixture, "main.js");
const makeInput = (secret: string, selector: string) =>
electronActiveObservationInputSchema.parse({
schema_version: 1,
executable_path: process.execPath,
application_path: applicationPath,
application_root: fixture,
args: ["--token", secret],
actions: [{ step_id: "click", kind: "click", selector }],
approved: true,
});
const provider = {
id: "rea-playwright-electron-active",
name: "REA Playwright active Electron observation provider",
version: "1",
};
const first = createElectronActiveEvidence(
makeInput("first-secret", "#first-secret"),
createElectronActiveObservationFixtureResult(applicationPath),
provider,
);
const second = createElectronActiveEvidence(
makeInput("second-secret", "#second-secret"),
createElectronActiveObservationFixtureResult(applicationPath),
provider,
);
expect(first.parameters.scenario_sha256).toBe(
second.parameters.scenario_sha256,
);
expect(JSON.stringify(first)).not.toContain("first-secret");
expect(JSON.stringify(first)).not.toContain("#first-secret");
expect(first.parameters.args).toEqual(["--token", "<redacted>"]);
});
it("imports an operator-provided cache layer through an explicit file mapping", async () => {
const application = await applicationFixture();
const cache = await createTestTempDirectory("rea-runtime-cache-static-");
@@ -42,6 +42,11 @@ describe("runtime configuration", () => {
expect(result.value.electronObservationEnabled).toBe(false);
expect(result.value.electronCdpEndpoints).toEqual([]);
expect(result.value.electronFileRoots).toEqual([]);
expect(result.value.electronAutomationPolicy).toEqual({
enabled: false,
executableRoots: [],
applicationRoots: [],
});
expect(result.value.v8InspectorObservationEnabled).toBe(false);
expect(result.value.v8InspectorEndpoints).toEqual([]);
expect(result.value.v8InspectorFileRoots).toEqual([]);
@@ -144,7 +149,64 @@ describe("runtime permission configuration", () => {
mount: false,
});
});
});
describe("active Electron permission configuration", () => {
it("builds a separately granted, no-network Electron automation ceiling", () => {
const result = parseConfig({
REA_ELECTRON_AUTOMATE_ENABLED: "true",
REA_ELECTRON_AUTOMATE_AUTO_GRANT: "false",
REA_ELECTRON_AUTOMATE_EXECUTABLE_ROOTS_JSON: '["/opt/electron"]',
REA_ELECTRON_AUTOMATE_APPLICATION_ROOTS_JSON: '["/tmp/apps"]',
});
if (!result.ok) throw result.error;
expect(result.value.electronAutomationPolicy).toEqual({
enabled: true,
executableRoots: ["/opt/electron"],
applicationRoots: ["/tmp/apps"],
});
expect(result.value.permissionCeilings).toContainEqual({
capability: "electron_automate",
roots: ["/tmp/apps"],
executables: ["/opt/electron"],
environment_names: [],
network: "external",
mount: false,
});
expect(result.value.administratorPermissionGrants).not.toContainEqual(
expect.objectContaining({ capability: "electron_automate" }),
);
const granted = parseConfig({
REA_ELECTRON_AUTOMATE_ENABLED: "true",
REA_ELECTRON_AUTOMATE_AUTO_GRANT: "true",
REA_ELECTRON_AUTOMATE_EXECUTABLE_ROOTS_JSON: '["/opt/electron"]',
REA_ELECTRON_AUTOMATE_APPLICATION_ROOTS_JSON: '["/tmp/apps"]',
});
if (!granted.ok) throw granted.error;
expect(granted.value.administratorPermissionGrants).toContainEqual(
expect.objectContaining({
capability: "electron_automate",
lifetime: "administrator",
}),
);
});
it("rejects relative active Electron roots", () => {
expect(
parseConfig({
REA_ELECTRON_AUTOMATE_APPLICATION_ROOTS_JSON: '["relative/apps"]',
}).ok,
).toBe(false);
expect(
parseConfig({
REA_ELECTRON_AUTOMATE_EXECUTABLE_ROOTS_JSON: '["relative/bin"]',
}).ok,
).toBe(false);
});
});
describe("runtime permission configuration", () => {
it("can configure a process-capture ceiling without an implicit grant", () => {
const result = parseConfig({
REA_PROCESS_CAPTURE_ENABLED: "true",
@@ -5,6 +5,7 @@ import {
createConformancePackage,
type ConformancePackage,
} from "../../../src/domain/conformancePackage.js";
import { createEvidence } from "../../../src/domain/evidence.js";
import {
replayConformancePackage,
type ScenarioReplayResult,
@@ -115,6 +116,41 @@ describe("conformance CI replay", () => {
expect(result.drift_detected).toBe(false);
});
it("retains the observed Evidence ID on the first drift", async () => {
const expected = createEvidence(
undefined,
{ id: "fixture-provider", name: "Fixture provider", version: "1" },
{ operation: "run", parameters: {}, result: { exit_code: 0 } },
);
const pkg = createConformancePackage({
...validPackage,
expected_evidence: [
{
scenario_id: "s1",
envelopes: [expected],
bundle: null,
required_dimensions: ["exit_code"],
},
],
});
const actualEvidenceId = `ev_${"3".repeat(64)}`;
const result = await replayConformancePackage(
pkg,
{
s1: {
evidence_id: actualEvidenceId,
normalized_result: { exit_code: 1 },
},
},
passingRunner,
);
expect(result.drift_detected).toBe(true);
expect(result.first_drift).toMatchObject({
dimension: "exit_code",
evidence_id: actualEvidenceId,
});
});
it("throws on invalid package", async () => {
await expect(replayConformancePackage({}, {})).rejects.toThrow(
/invalid conformance package/u,
@@ -62,7 +62,78 @@ describe("conformance trust gates", () => {
it("handles missing actual", () => {
const result = compareDimension("exit_code", 0, undefined);
expect(result.status).toBe("mismatch");
expect(result.status).toBe("unknown");
});
it("keeps semantic unknown and truncated values out of equivalence", () => {
expect(
compareDimension(
"process_tree",
{ processes: [] },
{ status: "unknown" },
),
).toMatchObject({ status: "unknown" });
expect(
compareDimension("process_tree", { processes: [] }, { truncated: true }),
).toMatchObject({ status: "truncated" });
expect(
compareDimension(
"process_tree",
{ status: "unknown" },
{ status: "unknown" },
),
).toMatchObject({ status: "unknown" });
});
it("projects Evidence envelopes and links a divergence to the observed ID", () => {
const expectedEvidenceId = `ev_${"1".repeat(64)}`;
const actualEvidenceId = `ev_${"2".repeat(64)}`;
const result = evaluateTrustGate(
contract,
{
evidence_id: expectedEvidenceId,
normalized_result: { exit_code: 0, stdout: "hello" },
},
{
evidence_id: actualEvidenceId,
normalized_result: { exit_code: 1, stdout: "hello" },
},
);
expect(result.verdict).toBe("fail");
expect(result.dimension_results[0]?.evidence_ids).toEqual([
actualEvidenceId,
expectedEvidenceId,
]);
expect(result.first_divergence).toMatchObject({
dimension: "exit_code",
evidence_id: actualEvidenceId,
});
});
it("scopes process residual unknowns without hiding complete dimensions", () => {
const processContract: VerifierContract = {
...contract,
dimensions: [
{ name: "exit_code", required: true, comparison: "exact" },
{ name: "process_tree", required: true, comparison: "semantic" },
],
};
const result = evaluateTrustGate(
processContract,
{ exit_code: 0, process_tree: { processes: [] } },
{
exit_code: 0,
process_tree: { processes: [] },
residual_unknowns: [{ scope: "process", reason: "event gap" }],
},
);
expect(result.verdict).toBe("unknown");
expect(result.dimension_results).toEqual(
expect.arrayContaining([
expect.objectContaining({ name: "exit_code", status: "match" }),
expect.objectContaining({ name: "process_tree", status: "unknown" }),
]),
);
});
it("passes when all dimensions match", () => {
@@ -5,6 +5,7 @@ import {
systemNoFollowOpenCapability,
type WindowsCapabilityDependencies,
} from "../../../../src/application/WindowsCapabilities.js";
import { WINDOWS_NATIVE_AUTHORITY_UNAVAILABLE_REASON } from "../../../../src/process/WindowsAuthority.js";
const dependencies = (
overrides: Partial<WindowsCapabilityDependencies> = {},
@@ -67,6 +68,23 @@ describe("Windows host capability report", () => {
},
pty: { available: false, reason: "probe unavailable" },
},
security: {
job_object_process_ownership: {
available: false,
reason: WINDOWS_NATIVE_AUTHORITY_UNAVAILABLE_REASON,
proof: "not-proven",
},
private_runtime_dacl: {
available: false,
reason: WINDOWS_NATIVE_AUTHORITY_UNAVAILABLE_REASON,
proof: "not-proven",
},
reparse_safe_path_admission: {
available: false,
reason: WINDOWS_NATIVE_AUTHORITY_UNAVAILABLE_REASON,
proof: "not-proven",
},
},
});
});
@@ -89,5 +107,26 @@ describe("Windows host capability report", () => {
reason: null,
});
expect(result.capabilities.private_acl.available).toBe(false);
expect(result.security.private_runtime_dacl).toMatchObject({
available: false,
proof: "not-proven",
});
});
it("does not promote an ordinary ACL probe into native authority", async () => {
const result = await probeWindowsCapabilities(
dependencies({
probePrivateAcl: () => ({ available: true, reason: null }),
}),
);
expect(result.capabilities.private_acl).toEqual({
available: true,
reason: null,
});
expect(result.security.private_runtime_dacl).toMatchObject({
available: false,
proof: "not-proven",
});
});
});
+20 -7
View File
@@ -5,19 +5,32 @@ const {
shell,
utilityProcess,
} = require("electron");
const { spawn } = require("node:child_process");
const windows = new Set();
app.on("open-url", (_event, url) => {
const deliverDeepLink = (url) => {
for (const window of windows) window.webContents.send("deep-link", url);
};
app.on("open-url", (_event, url) => deliverDeepLink(url));
app.on("second-instance", (_event, commandLine) => {
const url = commandLine.at(-1);
if (typeof url === "string") deliverDeepLink(url);
});
app.whenReady().then(() => {
const window = new BrowserWindow({
webPreferences: { preload: require.resolve("./preload.js") },
});
windows.add(window);
window.loadFile("renderer.html");
for (let index = 0; index < 2; index += 1) {
const window = new BrowserWindow({
webPreferences: { preload: require.resolve("./preload.js") },
});
windows.add(window);
window.loadFile("renderer.html");
window.webContents.on("render-process-gone", () => window.reload());
}
utilityProcess.fork(require.resolve("./utility.js"));
spawn(
process.env.REA_ELECTRON_NODE_EXECUTABLE ?? "node",
["-e", "setTimeout(() => {}, 100)"],
{ stdio: "ignore" },
);
ipcMain.handle("readiness:echo", (_event, value) => ({ value }));
window.webContents.on("render-process-gone", () => window.reload());
shell.openExternal("https://blocked.invalid").catch(() => undefined);
});
@@ -107,4 +107,12 @@ describe("localized README product facts", () => {
"pin persistent MCP registrations to the exact version",
);
});
it("documents the published MCP Registry installation path", async () => {
const content = await readFile(resolve("docs/installation.md"), "utf8");
expect(content).toContain("MCP Registry");
expect(content).toContain("io.github.morluto/rea");
expect(content).toContain('"command": "npx"');
expect(content).toContain('"args": ["-y", "rea-agents@latest", "mcp"]');
});
});
@@ -26,6 +26,16 @@ describe("release configuration", () => {
type: "generic",
path: "src/generatedPackageMetadata.ts",
},
{
type: "json",
path: "server.json",
jsonpath: "$.version",
},
{
type: "json",
path: "server.json",
jsonpath: "$.packages[0].version",
},
{
type: "json",
path: "docs/product-catalog.json",
@@ -61,6 +71,47 @@ describe("release configuration", () => {
expect(generated).toContain("x-release-please-version");
});
it("keeps the npm package and MCP Registry metadata aligned", async () => {
const packageJson = (await readJson("package.json")) as {
name: string;
version: string;
mcpName: string;
};
const serverJson = (await readJson("server.json")) as {
name: string;
version: string;
packages: Array<{
registryType: string;
registryBaseUrl: string;
identifier: string;
version: string;
runtimeHint: string;
transport: { type: string };
packageArguments: Array<{ type: string; value: string }>;
}>;
};
expect(packageJson).toMatchObject({
name: "rea-agents",
mcpName: "io.github.morluto/rea",
});
expect(serverJson).toMatchObject({
name: packageJson.mcpName,
version: packageJson.version,
packages: [
{
registryType: "npm",
registryBaseUrl: "https://registry.npmjs.org",
identifier: packageJson.name,
version: packageJson.version,
runtimeHint: "npx",
transport: { type: "stdio" },
packageArguments: [{ type: "positional", value: "mcp" }],
},
],
});
});
it("keeps TypeDoc unversioned and outside the tracked documentation tree", async () => {
await expect(readJson("typedoc.json")).resolves.toMatchObject({
includeVersion: false,
+61
View File
@@ -0,0 +1,61 @@
import { electronActiveObservationResultSchema } from "../../src/domain/electronActiveObservation.js";
/** Create a bounded active-capture result for MCP contract tests. */
export const createElectronActiveObservationFixtureResult = (
applicationPath: string,
) =>
electronActiveObservationResultSchema.parse({
schema_version: 1,
application: {
executable_path: process.execPath,
application_path: applicationPath,
electron_version: "test-electron",
process_ownership: "provider-owned",
cleanup: "terminated-owned-process",
},
actions: [
{
step_id: "submit",
kind: "click",
window_index: 0,
target: "window:1",
status: "completed",
elapsed_ms: 3,
error: null,
},
],
windows: [
{
window_id: "window:1",
web_contents_id: "webContents:1",
url: "file:///tmp/app.html",
title: "Fixture",
visible: true,
destroyed: false,
},
],
windows_truncated: false,
processes: {
items: [{ pid: 1234, type: "Browser", name: null, service_name: null }],
truncated: false,
},
ipc: {
events: [
{
sequence: 1,
kind: "main-handler-invocation",
channel: "readiness:echo",
argument_shapes: ["string"],
result_shape: "object",
process_type: "main",
error: false,
},
],
observed: 1,
retained: 1,
truncated: false,
},
limitations: [
"IPC payloads are represented only by bounded value shapes; values are never retained.",
],
});
+5 -2
View File
@@ -1,7 +1,10 @@
import { rename, rm, writeFile } from "node:fs/promises";
import { createServer } from "node:net";
const [
const configuration = JSON.parse(
process.env.REA_GHIDRA_FIXTURE_CONFIG ?? "null",
);
const {
endpointPath,
token,
runId,
@@ -10,7 +13,7 @@ const [
targetSha256,
transport,
mode = "success",
] = process.argv.slice(2);
} = configuration ?? {};
if (
endpointPath === undefined ||
+16 -6
View File
@@ -1,9 +1,17 @@
import { spawn } from "node:child_process";
const [mode, value = "0"] = process.argv.slice(2);
let keepAliveTimer;
let detachedChild;
const keepAlive = () => {
setInterval(() => undefined, 1_000);
keepAliveTimer = setInterval(() => undefined, 1_000);
};
const stopDetachedFixture = (signal) => {
if (keepAliveTimer !== undefined) clearInterval(keepAliveTimer);
if (detachedChild?.exitCode === null) detachedChild.kill(signal);
process.exitCode = signal === "SIGINT" ? 130 : 143;
};
const write = (stream, data) =>
@@ -38,7 +46,7 @@ switch (mode) {
keepAlive();
break;
case "detached-child": {
const child = spawn(
detachedChild = spawn(
process.execPath,
[
"-e",
@@ -47,11 +55,13 @@ switch (mode) {
{ detached: true, stdio: "ignore" },
);
await new Promise((resolve, reject) => {
child.once("spawn", resolve);
child.once("error", reject);
detachedChild.once("spawn", resolve);
detachedChild.once("error", reject);
});
await write(process.stdout, `ready:${child.pid}\n`);
child.unref();
process.once("SIGINT", () => stopDetachedFixture("SIGINT"));
process.once("SIGTERM", () => stopDetachedFixture("SIGTERM"));
await write(process.stdout, `ready:${detachedChild.pid}\n`);
detachedChild.unref();
keepAlive();
break;
}
@@ -37,7 +37,19 @@ describe("Vitest project configuration", () => {
expect(vitestConfiguration.test?.coverage?.enabled).toBe(false);
expect(vitestConfiguration.test?.reporters).toEqual(["default"]);
expect(vitestConfiguration.test?.retry).toBe(0);
expect(MAX_TEST_WORKERS).toBe(Math.min(2, availableParallelism()));
const local = process.env.CI !== "true";
expect(MAX_TEST_WORKERS).toBe(
local ? 1 : Math.min(2, availableParallelism()),
);
expect(
TEST_PROJECTS.every(
({ fileParallelism, maxWorkers, sequence }) =>
maxWorkers === MAX_TEST_WORKERS &&
(local
? fileParallelism === false && sequence?.groupOrder !== undefined
: true),
),
).toBe(true);
expect(TEST_PROJECTS.map(({ name }) => name).sort()).toEqual(
EXPECTED_PROJECTS,
);