chore(plugins): sync the captured final review base

This commit is contained in:
morluto
2026-10-13 21:50:53 +08:00
253 changed files with 12485 additions and 1407 deletions
@@ -366,16 +366,11 @@ it("rejects overlapping ZIP member data ranges through artifact inventory", asyn
bytes.writeUInt32LE(firstLocalOffset, second + 42);
await writeFile(path, bytes);
const target = await parseBinaryTarget(path);
if (!target.ok) throw target.error;
const result = await withArtifactClient(target.value, (client) =>
client.execute("inventory_artifact", {}),
await expectInventoryFailure(
path,
"format",
"ZIP archive is malformed: Overlapping entry found",
);
expect(result).toMatchObject({
ok: false,
error: { _tag: "ArtifactOperationError", reason: "io" },
});
});
it("preserves encrypted-member and corrupt-CRC observations", async () => {
@@ -438,16 +433,11 @@ it("preserves encrypted-member and corrupt-CRC observations", async () => {
bytes[dataOffset] = firstByte ^ 1;
await writeFile(corruptPath, bytes);
const corruptTarget = await parseBinaryTarget(corruptPath);
if (!corruptTarget.ok) throw corruptTarget.error;
const corruptResult = await withArtifactClient(
corruptTarget.value,
(client) => client.execute("inventory_artifact", {}),
await expectInventoryFailure(
corruptPath,
"format",
"ZIP archive is malformed: Invalid compressed data",
);
expect(corruptResult).toMatchObject({
ok: false,
error: { _tag: "ArtifactOperationError", reason: "io" },
});
});
it("rejects a truncated ZIP through artifact inventory", async () => {
@@ -455,17 +445,51 @@ it("rejects a truncated ZIP through artifact inventory", async () => {
const path = join(root, "truncated.zip");
await writeFile(path, Buffer.from([0x50, 0x4b, 0x03, 0x04]));
await expectInventoryFailure(
path,
"format",
"ZIP archive is malformed: File format is not recognized",
);
});
it("reports an unsupported ZIP compression method as unavailable", async () => {
const root = await createTestTempDirectory("rea-zip-method-");
const path = join(root, "lzma.zip");
const writer = new ZipWriter(new Uint8ArrayWriter());
await writer.add("data.txt", new TextReader("member bytes"), { level: 0 });
const bytes = Buffer.from(await writer.close());
// Declare LZMA (14) in both headers; REA reads only stored and Deflate data.
const localHeader = bytes.indexOf(Buffer.from([0x50, 0x4b, 0x03, 0x04]));
const centralHeader = bytes.indexOf(Buffer.from([0x50, 0x4b, 0x01, 0x02]));
if (localHeader < 0 || centralHeader < 0)
throw new Error("Expected ZIP local and central headers");
bytes.writeUInt16LE(14, localHeader + 8);
bytes.writeUInt16LE(14, centralHeader + 10);
await writeFile(path, bytes);
await expectInventoryFailure(
path,
"unavailable",
"ZIP archive uses an unsupported feature: Compression method not supported",
);
});
/** Inventory one archive through the provider and expect a typed failure. */
const expectInventoryFailure = async (
path: string,
reason: string,
detail: string,
): Promise<void> => {
const target = await parseBinaryTarget(path);
if (!target.ok) throw target.error;
const result = await withArtifactClient(target.value, (client) =>
client.execute("inventory_artifact", {}),
);
expect(result).toMatchObject({
ok: false,
error: { _tag: "ArtifactOperationError", reason: "io" },
error: { _tag: "ArtifactOperationError", reason, detail },
});
});
};
const writeSingleEntryZip = async (
path: string,
@@ -515,6 +515,10 @@ it.each([
"src/windows/Example.ts",
{ code: true, runtime: true, package: true, apple: false, evm: false },
],
[
"src/domain/javascript/javascriptRuntimeStaticCandidates.ts",
{ code: true, runtime: true, package: true, javascript_recovery: true },
],
["install.sh", { code: true, runtime: true, package: true, evm: false }],
[
".agents/skills/reverse-engineer-anything/SKILL.md",
@@ -262,8 +262,8 @@ it("binds provider build reuse to the current run while keeping standalone dispa
),
),
);
const download = action.runs.steps.find(
(step) => step.uses === "actions/download-artifact@v4",
const download = action.runs.steps.find((step) =>
step.uses?.startsWith("actions/download-artifact@"),
);
expect(download?.with).toEqual({
name: "${{ inputs.build_cache_artifact }}",
@@ -71,6 +71,7 @@ describe("client configuration filesystem lifecycle", () => {
"pi",
"hermes",
"qoder",
"droid",
"zcode",
"dsh",
"grok_bot",
@@ -1,5 +1,5 @@
import { parseConfig } from "../../../src/config/parseConfig.js";
import { writeFile } from "node:fs/promises";
import { symlink, writeFile } from "node:fs/promises";
import { basename, dirname, join } from "node:path";
import { describe, expect, it, vi } from "vitest";
@@ -14,7 +14,7 @@ import type {
import type { DirectAnalysisDependencies } from "../../../src/application/DirectAnalysisDependencies.js";
import { createAnalysisProfile } from "../../../src/domain/analysisProfile.js";
import { createAnalysisExecution } from "../../../src/application/AnalysisProvider.js";
import { ok } from "../../../src/domain/result.js";
import { err, ok } from "../../../src/domain/result.js";
import {
readAnalysisSnapshot,
writeAnalysisSnapshot,
@@ -40,6 +40,7 @@ import {
} from "../../fixtures/binarySession.js";
import { BinarySession } from "../../../src/application/binary/BinarySession.js";
import { OwnedStagedOutput } from "../../../src/filesystem/OwnedStagedOutput.js";
import { ProviderAdapterError } from "../../../src/domain/providerAdapterError.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import {
CAPABILITIES as GHIDRA_CAPABILITIES,
@@ -396,7 +397,85 @@ describe("snapshot output cleanup lifecycle", () => {
});
});
const verifyWindowsSnapshotAdmission = async (
selectedPath: "direct" | "junction",
): Promise<void> => {
const fixture = await createSnapshotReplayFixture(
"rea-direct-snapshot-junction-",
);
const rawPath = join(dirname(fixture.path), "image.bin");
await writeFile(rawPath, Buffer.from("a92a60", "hex"));
const linked = join(dirname(fixture.path), "linked");
const linkedPath = join(linked, basename(rawPath));
const identity = { ...GHIDRA_PROVIDER_IDENTITY, version: "12.1.4" };
const profile = createAnalysisProfile(identity, {
fixture: true,
});
const baseProvider = fixture.createProvider({
identity,
profile,
supportedOperations: ["search_strings"],
});
let rejectAdmission = false;
const provider: AnalysisProvider = {
...baseProvider,
createClient: (target, profile, context) => {
const client = baseProvider.createClient(target, profile, context);
return {
...client,
execute: (operation, parameters, options) =>
rejectAdmission && operation === "search_strings"
? Promise.resolve(
err(new ProviderAdapterError("ghidra", operation)),
)
: client.execute(operation, parameters, options),
};
},
};
const dependencies = fixture.dependencies(provider);
const arguments_ = { pattern: "fixture", document: "fixture" };
const options = {
snapshotPath: fixture.snapshotPath,
formatHint: "raw-binary" as const,
architecture: "6502" as const,
entryPoint: "0x8001",
};
const first = await runDirectAnalysis(
dependencies,
rawPath,
"search_strings",
arguments_,
options,
);
expect(first).toMatchObject({ operation: "search_strings" });
expect(fixture.starts).toHaveLength(1);
if (selectedPath === "junction")
await symlink(dirname(fixture.path), linked, "junction");
rejectAdmission = true;
const second = await runDirectAnalysis(
dependencies,
selectedPath === "junction" ? linkedPath : rawPath,
"search_strings",
arguments_,
options,
);
expect(second).toMatchObject({ error: "Analysis failed" });
expect(fixture.starts).toHaveLength(2);
expect(
fixture.calls.filter((call) => call === "search_strings"),
).toHaveLength(1);
};
describe("direct analysis composed snapshot replay", () => {
it.skipIf(process.platform !== "win32")(
"does not replay a CLI snapshot through a Windows junction",
() => verifyWindowsSnapshotAdmission("junction"),
);
it.skipIf(process.platform !== "win32")(
"does not replay a CLI snapshot before native admission on a canonical path",
() => verifyWindowsSnapshotAdmission("direct"),
);
it.each([
{
tool: "search_strings",
@@ -516,7 +595,7 @@ describe("Ghidra composed workflow snapshot replay", () => {
{ tool: "inspect_native_api", arguments: { procedure: "0x1000" } },
{ tool: "trace_feature", arguments: { query: "fixture" } },
] as const)(
"persists and replays $tool with production Ghidra capability policies",
"persists $tool with production Ghidra capability policies",
async ({ tool, arguments: parameters }) => {
const fixture = await createSnapshotReplayFixture("rea-ghidra-workflow-");
const profile = createAnalysisProfile(
@@ -554,8 +633,14 @@ describe("Ghidra composed workflow snapshot replay", () => {
{ snapshotPath: fixture.snapshotPath },
);
expect(replay).toEqual(first);
expect(fixture.starts).toHaveLength(1);
expect(fixture.calls).toEqual(initialCalls);
if (process.platform === "win32") {
// The first provider call in a new CLI session admits its source.
expect(fixture.starts).toHaveLength(2);
expect(fixture.calls.length).toBeGreaterThan(initialCalls.length);
} else {
expect(fixture.starts).toHaveLength(1);
expect(fixture.calls).toEqual(initialCalls);
}
},
);
});
@@ -0,0 +1,167 @@
import { mkdir, readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { readClientRegistrationStatuses } from "../../../src/application/ClientRegistrationStatus.js";
import { npxRegistrationCommand } from "../../../src/application/ClientRegistrationIdentity.js";
import { configureClientConfiguration } from "../../../src/application/SetupClientConfiguration.js";
import { skillDestinations } from "../../../src/application/SetupSkill.js";
import { supportedClients } from "../../../src/application/SupportedClients.js";
import { systemUninstallHost } from "../../../src/application/Uninstall.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { clearClientLocationEnvironment } from "../../fixtures/clientEnvironment.js";
/**
* The registration command setup writes on the host running the tests. Windows
* wraps it in `cmd.exe /d /c`, so the expected entry follows the host too.
*/
const command = npxRegistrationCommand(process.platform);
beforeEach(clearClientLocationEnvironment);
afterEach(() => vi.unstubAllEnvs());
const droidPath = (
home: string,
platform: NodeJS.Platform = "linux",
env: Parameters<typeof supportedClients>[2] = {},
) => supportedClients(home, platform, env).find(({ name }) => name === "droid");
describe("Factory Droid configuration paths", () => {
it("resolves the user MCP config file and marker directory", () => {
expect(droidPath("/home/a")).toEqual({
name: "droid",
displayName: "Factory Droid",
configPath: join("/home/a", ".factory", "mcp.json"),
markerPath: join("/home/a", ".factory"),
format: "json",
});
expect(droidPath("/Users/a", "darwin")?.configPath).toBe(
join("/Users/a", ".factory", "mcp.json"),
);
expect(droidPath("C:\\Users\\a", "win32")?.configPath).toBe(
join("C:\\Users\\a", ".factory", "mcp.json"),
);
});
it("resolves the personal skills directory beside the config root", () => {
expect(
skillDestinations("/home/a", ["droid"]).map(({ path }) => path),
).toEqual([
join("/home/a", ".factory", "skills", "reverse-engineer-anything"),
]);
});
});
describe("Factory Droid JSON registration", () => {
const droidClient = async () => {
const home = await createTestTempDirectory("rea-droid-");
const client = droidPath(home, process.platform);
if (client?.markerPath === undefined)
throw new Error("missing Factory Droid client");
await mkdir(client.markerPath, { recursive: true });
return { home, client };
};
it("upserts rea into mcpServers while preserving unrelated servers and permissions", async () => {
const { home, client } = await droidClient();
await writeFile(
client.configPath,
`{
"mcpServers": {
"other": {
"type": "stdio",
"command": "other",
"args": [],
"disabled": false
}
},
"persistentPermissions": {
"servers": {
"other": { "approvedAt": "2026-01-01T00:00:00.000Z" }
}
}
}`,
);
expect(
(await configureClientConfiguration(client, {}, command)).status,
).toBe("configured");
const parsed = JSON.parse(await readFile(client.configPath, "utf8"));
expect(parsed.mcpServers.other).toEqual({
type: "stdio",
command: "other",
args: [],
disabled: false,
});
expect(parsed.persistentPermissions).toEqual({
servers: { other: { approvedAt: "2026-01-01T00:00:00.000Z" } },
});
expect(parsed.mcpServers.rea).toEqual({
command: command[0],
args: command.slice(1),
});
expect(await configureClientConfiguration(client, {}, command)).toEqual({
status: "unchanged",
});
expect(
(
await readClientRegistrationStatuses(home, undefined, {
platform: process.platform,
environment: {},
})
).find(({ client }) => client === "droid"),
).toMatchObject({ state: "aligned", command });
});
it("creates the mcpServers table in an existing config file without servers", async () => {
const { client } = await droidClient();
await writeFile(
client.configPath,
JSON.stringify({ persistentPermissions: { servers: {} } }, null, 2),
);
expect(
(await configureClientConfiguration(client, {}, command)).status,
).toBe("configured");
const parsed = JSON.parse(await readFile(client.configPath, "utf8"));
expect(parsed.persistentPermissions).toEqual({ servers: {} });
expect(parsed.mcpServers.rea).toEqual({
command: command[0],
args: command.slice(1),
});
});
it("registers into an empty config file", async () => {
const { client } = await droidClient();
await writeFile(client.configPath, "");
expect(
(await configureClientConfiguration(client, {}, command)).status,
).toBe("configured");
const parsed = JSON.parse(await readFile(client.configPath, "utf8"));
expect(parsed.mcpServers.rea).toEqual({
command: command[0],
args: command.slice(1),
});
});
it("removes only the rea entry on uninstall", async () => {
const { home, client } = await droidClient();
await writeFile(
client.configPath,
JSON.stringify(
{ mcpServers: { other: { command: "other-server" } } },
null,
2,
),
);
await configureClientConfiguration(client, {}, command);
expect((await systemUninstallHost(home).removeClient(client)).status).toBe(
"removed",
);
const parsed = JSON.parse(await readFile(client.configPath, "utf8"));
expect(parsed.mcpServers.other).toEqual({ command: "other-server" });
expect(parsed.mcpServers.rea).toBeUndefined();
});
});
@@ -1,5 +1,5 @@
import { mkdir, readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { join, resolve } from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import {
@@ -37,28 +37,76 @@ const dshClient = (
env: Parameters<typeof supportedClients>[2],
platform: NodeJS.Platform = "linux",
) =>
supportedClients(join("/home/a"), platform, env).find(
supportedClients(resolve("/home/a"), platform, env).find(
({ name }) => name === "dsh",
);
describe("DeepSeek Harness configuration paths", () => {
it.each([
[undefined, ".dsh", ".agents", "shared"],
["", ".dsh", ".agents", "shared"],
[" \t ", ".dsh", ".agents", "shared"],
["~", "", "", "dsh"],
["~/selected home", "selected home", "selected home", "dsh"],
["~\\selected home", "selected home", "selected home", "dsh"],
] as const)(
"resolves Harness and agents roots for %j",
(override, dshRoot, agentsRoot, client) => {
const home = resolve("/home/a");
const environment = { DSH_HOME: override, DSH_AGENTS_HOME: override };
expect(
supportedClients(home, process.platform, environment).find(
({ name }) => name === "dsh",
),
).toMatchObject({
configPath: join(home, dshRoot, "cordis.patch.yml"),
markerPath: join(home, dshRoot),
});
expect(clientSkillDirectories(home, ["dsh"], environment)).toEqual([
{ client, directory: join(home, agentsRoot, "skills") },
]);
},
);
it.each(["relative home", " literal home ", "~someone"])(
"resolves a literal root %j relative to cwd without trimming it",
(override) => {
const home = resolve("/home/a");
const root = resolve(override);
const environment = { DSH_HOME: override, DSH_AGENTS_HOME: override };
expect(
supportedClients(home, process.platform, environment).find(
({ name }) => name === "dsh",
),
).toMatchObject({
configPath: join(root, "cordis.patch.yml"),
markerPath: root,
});
expect(clientSkillDirectories(home, ["dsh"], environment)).toEqual([
{ client: "dsh", directory: join(root, "skills") },
]);
},
);
it("resolves the home Cordis patch under the Harness home", () => {
expect(dshClient({})).toEqual({
name: "dsh",
displayName: "DeepSeek Harness",
configPath: join("/home/a", ".dsh", "cordis.patch.yml"),
markerPath: join("/home/a", ".dsh"),
configPath: resolve("/home/a", ".dsh", "cordis.patch.yml"),
markerPath: resolve("/home/a", ".dsh"),
format: "dsh",
});
// The home patch applies to every profile; DSH_HOME relocates it.
expect(dshClient({ DSH_HOME: "/custom/harness" })?.configPath).toBe(
join("/custom/harness", "cordis.patch.yml"),
resolve("/custom/harness", "cordis.patch.yml"),
);
expect(
clientSkillDirectories(join("/home/a"), ["dsh"], {
DSH_AGENTS_HOME: "/custom/agents",
}),
).toEqual([{ client: "dsh", directory: join("/custom/agents", "skills") }]);
).toEqual([
{ client: "dsh", directory: resolve("/custom/agents", "skills") },
]);
});
});
@@ -87,3 +87,43 @@ it.each([
);
},
);
it("bounds the Java version probe and reports an over-budget probe as a failed Java check", async () => {
const root = await createTestTempDirectory("rea-java-probe-bound-");
const configuredHome = join(root, "selected-jdk");
const installDir = join(root, "ghidra");
await mkdir(join(installDir, "Ghidra"), { recursive: true });
await writeFile(
join(installDir, "Ghidra", "application.properties"),
`application.version=${SUPPORTED_GHIDRA_VERSION}\napplication.java.min=17\n`,
);
// A chatty or hostile JVM that overruns the capture budget: spawnSync reports
// ENOBUFS, which the probe already treats as a failed observation.
mockSpawnSync.mockReturnValue({
stdout: "",
stderr: "java.version = 21.0.11\n",
status: null,
error: Object.assign(new Error("spawnSync /java ENOBUFS"), {
code: "ENOBUFS",
}),
});
const inspection = inspectGhidraInstallation({
environment: {},
installDir,
javaHome: configuredHome,
});
const [, , options] = mockSpawnSync.mock.calls[0] as [
string,
readonly string[],
{ readonly maxBuffer?: number },
];
expect(options.maxBuffer).toBe(1024 * 1024);
expect(inspection.javaVersion).toBeNull();
expect(inspection.javaHome).toBe(configuredHome);
expect(inspection.checks.find(({ name }) => name === "java")).toMatchObject({
status: "failed",
code: "runtime_missing",
});
});
@@ -237,6 +237,38 @@ mcp_servers:
expect(await readFile(client.configPath, "utf8")).toBe(original);
});
it("keeps unrelated numbers as written, including Discord IDs", async () => {
const { home, client } = await hermesClient();
// Hermes reads these exactly: two IDs one apart, an octal mode, a float.
const original = `discord:
free_response_channels:
- 1187654321098765432
channel_prompts:
1187654321098765433: Build questions.
1187654321098765434: Release questions.
mode: 0600
min_score: 0.0000001
mcp_servers:
other:
command: other-server
`;
await writeFile(client.configPath, original);
expect(
(await configureClientConfiguration(client, {}, command)).status,
).toBe("configured");
const text = await readFile(client.configPath, "utf8");
expect(text.startsWith(original)).toBe(true);
expect(parseYaml(text, { intAsBigInt: true })).toMatchObject({
mcp_servers: {
rea: { command: command[0], args: command.slice(1), enabled: true },
},
});
expect((await systemUninstallHost(home).removeClient(client)).status).toBe(
"removed",
);
expect(await readFile(client.configPath, "utf8")).toBe(original);
});
it("creates config.yaml when Hermes has no configuration yet", async () => {
const { client } = await hermesClient();
expect(
@@ -1060,6 +1060,142 @@ describe("NIBArchive UIKit event connections", () => {
"UIRuntimeEventConnection",
);
});
it("reports a runtime connection with no resolvable owner as an omission", async () => {
const root = await createTestTempDirectory("rea-ib-ownerless-");
const bundle = join(root, "Example.app");
await mkdir(bundle, { recursive: true });
// The connector is recognized by class, but carries no UISource reference,
// so no connection can be projected from it.
await writeFile(
join(bundle, "Cell.nib"),
encodeNibArchiveFixture({
classes: [
"UIProxyObject",
"UIClassSwapper",
"UIButton",
"UIRuntimeEventConnection",
"NSString",
],
objects: [
{ classIndex: 0, values: { UIProxiedObjectIdentifier: { ref: 5 } } },
{ classIndex: 1, values: { UIClassName: { ref: 6 } } },
{ classIndex: 2, values: {} },
{
classIndex: 3,
values: { UIDestination: { ref: 1 }, UIEventMask: 64 },
},
{ classIndex: 2, values: {} },
{ classIndex: 4, values: { "NS.bytes": "IBFilesOwner" } },
{ classIndex: 4, values: { "NS.bytes": "BuildCell" } },
],
}),
);
const analysis = await analyzeInterfaceBuilderBundle({
bundlePath: bundle,
targetSha256: "e".repeat(64),
});
expect(analysis.graph.coverage).toContainEqual(
expect.objectContaining({
facet: "connections:Cell.nib",
status: "partial",
reason: "connection_unresolved",
examined: 0,
omitted: 1,
}),
);
// The keyed-archive producer counts a recognized connector it cannot emit,
// so this producer has to report the same document total for the same
// connector rather than zero.
expect(analysis.documents).toContainEqual(
expect.objectContaining({
relative_path: "Cell.nib",
connection_count: 1,
}),
);
expect(analysis.graph.truncated).toBe(true);
expect(analysis.limitations).toContain(
"Some recognized NIBArchive connectors declare no resolvable owner; they carry no connection evidence and are reported as omissions.",
);
});
});
describe("NIBArchive ownerless connector accounting", () => {
it("keeps a connection dropped by the limit reported as a limit", async () => {
const root = await createTestTempDirectory("rea-ib-ownerless-limit-");
const bundle = join(root, "Example.app");
await mkdir(bundle, { recursive: true });
// Two resolvable connectors and one ownerless connector with the limit
// below the resolvable count, so this facet has both causes at once. Only a
// higher limit recovers the dropped connection, so that is the reason the
// caller needs, exactly as the keyed-archive producer reports it.
await writeFile(
join(bundle, "Cell.nib"),
encodeNibArchiveFixture({
classes: [
"UIProxyObject",
"UIClassSwapper",
"UIButton",
"UIRuntimeEventConnection",
"NSString",
],
objects: [
{ classIndex: 0, values: { UIProxiedObjectIdentifier: { ref: 5 } } },
{ classIndex: 1, values: { UIClassName: { ref: 6 } } },
{ classIndex: 2, values: {} },
{
classIndex: 3,
values: {
UISource: { ref: 2 },
UIDestination: { ref: 1 },
UILabel: { ref: 7 },
UIEventMask: 64,
},
},
{ classIndex: 2, values: {} },
{ classIndex: 4, values: { "NS.bytes": "IBFilesOwner" } },
{ classIndex: 4, values: { "NS.bytes": "BuildCell" } },
{ classIndex: 4, values: { "NS.bytes": "buildTapped:" } },
{
classIndex: 3,
values: {
UISource: { ref: 4 },
UIDestination: { ref: 1 },
UILabel: { ref: 7 },
},
},
{
classIndex: 3,
values: { UIDestination: { ref: 1 }, UIEventMask: 64 },
},
],
}),
);
const analysis = await analyzeInterfaceBuilderBundle({
bundlePath: bundle,
targetSha256: "e".repeat(64),
limits: { max_connections: 1 },
});
expect(analysis.graph.coverage).toContainEqual(
expect.objectContaining({
facet: "connections:Cell.nib",
status: "partial",
reason: "connection_limit_reached",
examined: 1,
omitted: 2,
}),
);
expect(analysis.documents).toContainEqual(
expect.objectContaining({
relative_path: "Cell.nib",
connection_count: 3,
}),
);
});
});
// This exact file is already selected by the unchanged native Apple CI lane.
@@ -388,7 +388,7 @@ it("produces deterministic ASAR graphs with unpacked native linkage and complete
await mkdir(source);
await writeJavaScriptArtifactFixture(source);
const archive = join(root, "app.asar");
await createPackageWithOptions(source, archive, { unpack: "**/*.node" });
await createPackageWithOptions(source, archive, { unpack: "*.node" });
const first = await reconstructJavaScriptArtifact({
input_path: archive,
@@ -487,7 +487,7 @@ it("keeps ASAR analysis usable when unpacked native companion bytes are absent",
await mkdir(source);
await writeJavaScriptArtifactFixture(source);
const archive = join(root, "app.asar");
await createPackageWithOptions(source, archive, { unpack: "**/*.node" });
await createPackageWithOptions(source, archive, { unpack: "*.node" });
await rm(join(`${archive}.unpacked`, "native", "addon.node"));
const snapshot = await scanArtifactInventory(archive);
@@ -515,7 +515,7 @@ it("recurses into filesystem-backed ASAR containers without losing container-rel
const resources = join(outer, "resources");
await mkdir(resources, { recursive: true });
await createPackageWithOptions(source, join(resources, "app.asar"), {
unpack: "**/*.node",
unpack: "*.node",
});
const result = await reconstructJavaScriptArtifact({
@@ -444,73 +444,97 @@ describe("JavaScript application workflow error diagnostics", () => {
});
});
const RUNTIME_PATH_CASES = [
{
name: "case-sensitive POSIX input root",
root: null,
path: "/applications/Example.app/Contents/Resources/app/renderer.js",
status: "unknown",
basis: "none",
},
{
name: "case-sensitive POSIX mapping root",
root: "/runtime/App",
path: "/runtime/app/renderer.js",
status: "unknown",
basis: "none",
},
{
name: "matching POSIX mapping root",
root: "/runtime/App",
path: "/runtime/App/renderer.js",
status: "matched",
basis: "operator-file-mapping",
},
{
name: "case-insensitive Windows mapping root",
root: String.raw`C:\runtime\App`,
path: String.raw`c:\runtime\app\renderer.js`,
status: "matched",
basis: "operator-file-mapping",
},
] as const;
describe("JavaScript runtime reconciliation local paths", () => {
it.each([
{
name: "case-sensitive POSIX input root",
root: null,
path: "/applications/Example.app/Contents/Resources/app/renderer.js",
status: "unknown",
},
{
name: "case-sensitive POSIX mapping root",
root: "/runtime/App",
path: "/runtime/app/renderer.js",
status: "unknown",
},
{
name: "matching POSIX mapping root",
root: "/runtime/App",
path: "/runtime/App/renderer.js",
status: "matched",
},
{
name: "case-insensitive Windows mapping root",
root: String.raw`C:\runtime\App`,
path: String.raw`c:\runtime\app\renderer.js`,
status: "matched",
},
])("uses $name on every host", ({ root, path, status }) => {
const base = JAVASCRIPT_RUNTIME_RECONCILIATION_EXAMPLE;
const original = base.runtime_observations[0]!;
const inspection = electronPageInspectionSchema.parse(
original.normalized_result,
);
const runtime = createEvidence(undefined, original.provider, {
predicateType: original.predicate_type,
operation: original.operation,
parameters: { ...original.parameters, include_script_sources: false },
result: {
...inspection,
scripts: {
...inspection.scripts,
items: inspection.scripts.items.map((script) => ({
...script,
file_path: path,
source: { included: false, reason: "not-requested" },
})),
it.each(RUNTIME_PATH_CASES)(
"uses $name on every host",
({ root, path, status, basis }) => {
const base = JAVASCRIPT_RUNTIME_RECONCILIATION_EXAMPLE;
const original = base.runtime_observations[0]!;
const inspection = electronPageInspectionSchema.parse(
original.normalized_result,
);
// Keep target and script coordinates consistent so an unrelated target
// cannot activate the static layer after its script mapping was rejected.
const runtime = createEvidence(undefined, original.provider, {
predicateType: original.predicate_type,
operation: original.operation,
parameters: { ...original.parameters, include_script_sources: false },
result: {
...inspection,
target: { ...inspection.target, file_path: path },
scripts: {
...inspection.scripts,
items: inspection.scripts.items.map((script) => ({
...script,
file_path: path,
source: { included: false, reason: "not-requested" },
})),
},
},
},
confidence: original.confidence,
authority: original.authority,
});
const reconciled = reconcileJavaScriptRuntimeEvidence({
static_layers: base.static_layers.map((layer) => ({
...layer,
runtime_mappings: root === null ? [] : [{ kind: "file-root", root }],
})),
runtime_observations: [runtime],
});
if (!reconciled.ok) throw reconciled.error;
const result = javascriptRuntimeReconciliationResultSchema.parse(
reconciled.value.normalized_result,
);
expect(
result.reconciliations.find(
({ entity_kind }) => entity_kind === "script",
),
).toMatchObject({ status });
});
confidence: original.confidence,
authority: original.authority,
});
const reconciled = reconcileJavaScriptRuntimeEvidence({
static_layers: base.static_layers.map((layer) => ({
...layer,
runtime_mappings: root === null ? [] : [{ kind: "file-root", root }],
})),
runtime_observations: [runtime],
});
if (!reconciled.ok) throw reconciled.error;
const result = javascriptRuntimeReconciliationResultSchema.parse(
reconciled.value.normalized_result,
);
expect(
result.reconciliations.find(
({ entity_kind }) => entity_kind === "script",
),
).toMatchObject({ status, basis });
expect(
result.static_load_states.find(
({ kind }) => kind === "javascript-asset",
),
).toMatchObject(
status === "matched"
? { status: "loaded", reason: "runtime-script-correspondence" }
: { status: "unknown", reason: "layer-outside-runtime-scope" },
);
expect(result.static_layers[0]?.runtime_mappings).toEqual(
root === null ? [] : [{ kind: "file-root", root, artifact_prefix: "" }],
);
},
);
it("resolves relative file mapping roots before deriving result Evidence", () => {
const absoluteRoot = resolve(process.cwd(), "runtime-cache-fixture");
@@ -105,6 +105,34 @@ it("keeps a contradicted nested ASAR opaque during JavaScript reconstruction", a
expect(result.graph.coverage.omitted_count).toBeNull();
});
it("keeps an ASAR-named file without an ASAR header opaque during JavaScript reconstruction", async () => {
const root = await createTestTempDirectory("rea-opaque-asar-name-");
await writeFile(join(root, "main.js"), "export const outer = true;\n");
// Inventory records this file as ordinary bytes and does not expand it.
await writeFile(join(root, "ordinary.asar"), "ordinary bytes");
const snapshot = await scanCanonicalArtifactInventory(root, {});
const reader = createJavaScriptArtifactReader(root, "directory");
try {
const read = await readJavaScriptArtifactFiles(reader, snapshot);
expect(read.files.map(({ path }) => path)).toEqual(["main.js"]);
expect(read.containers).toEqual([]);
} finally {
await reader.close();
}
const analyzed = await analyzeJavaScriptApplication({
input_path: root,
format: "directory",
});
if (!analyzed.ok) throw analyzed.error;
const result = javascriptApplicationAnalysisResultSchema.parse(
analyzed.value.normalized_result,
);
expect(result.statistics.nested_asar_containers).toBe(0);
expect(result.integrity_contradictions).toEqual([]);
});
it("retains semantic resource limits alongside recorded integrity contradictions", async () => {
const { archive } = await createStrippedAsarAddon([
{ path: "app.js", contents: primitiveCandidateExpansionSource() },
@@ -1,5 +1,11 @@
import { createHash } from "node:crypto";
import { readFile, writeFile } from "node:fs/promises";
import {
mkdir,
readFile,
realpath,
symlink,
writeFile,
} from "node:fs/promises";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
@@ -7,6 +13,37 @@ import { parseBinaryTarget } from "../../../src/application/BinaryTargetResolver
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
describe("raw-binary admission", () => {
it("preserves the requested raw path for Windows reparse admission", async () => {
const directory = await createTestTempDirectory("rea-raw-linked-");
const actual = join(directory, "actual");
const linked = join(directory, "linked");
await mkdir(actual);
const bytes = Buffer.from("a90160", "hex");
await writeFile(join(actual, "fixture.bin"), bytes);
await symlink(
actual,
linked,
process.platform === "win32" ? "junction" : "dir",
);
const requested = join(linked, "fixture.bin");
const canonical = await realpath(requested);
const target = await parseBinaryTarget("linked/fixture.bin", {
cwd: directory,
formatHint: "raw-binary",
architecture: "6502",
entryPoint: "0x8000",
});
expect(target).toMatchObject({
ok: true,
value: {
path: canonical,
sourcePath: process.platform === "win32" ? requested : canonical,
sha256: createHash("sha256").update(bytes).digest("hex"),
format: "raw-binary",
architecture: "6502",
},
});
});
it("requires explicit architecture and entry even with a misleading suffix", async () => {
const directory = await createTestTempDirectory("rea-raw-target-");
const path = join(directory, "fixture.js");
@@ -4,9 +4,35 @@ import { describe, expect, it } from "vitest";
import { systemDoctorHost } from "../../../src/application/Doctor.js";
import { parseBinaryTarget } from "../../../src/application/BinaryTargetResolver.js";
import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js";
import { pe } from "../../../src/domain/binaryTarget.fixture.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
describe("executable format refusal diagnostics", () => {
it.each([
[0x01a6, "0x01a6"],
[0x0000, "0x0000"],
[0xffff, "0xffff"],
] as const)(
"retains unsupported PE machine %i in the refusal",
async (machine, expectedMachine) => {
const directory = await createTestTempDirectory("rea-target-pe-machine-");
const path = join(directory, "unsupported.exe");
const bytes = pe(0x014c);
bytes.writeUInt16LE(machine, 0x44);
await writeFile(path, bytes);
const result = await parseBinaryTarget(path);
if (result.ok) throw new Error("unsupported PE target was admitted");
const reason = `unsupported PE architecture (COFF machine ${expectedMachine})`;
expect(projectAnalysisError(result.error)).toMatchObject({
code: "target_unavailable",
category: "unsupported_target",
message: `Cannot open artifact: ${reason}.`,
details: { reason, constraint: "file_format_rejected" },
});
},
);
it.each(["NE", "LE", "LX"] as const)(
"reports unsupported %s executables without path advice",
async (signature) => {