refactor: consolidate boundary semantics and prune redundant tests

Share parser modes and collision-free composite keys, enforce architecture guards, and consolidate redundant unit assertions into filesystem, CLI, MCP, and producer-backed workflows. Preserve concurrent upstream boundary fixes and exclude legacy Objective-C class-name bookkeeping labels.

Validation: source/composition suites (3358 passing), focused canonical digest and MCP checks, typecheck/lint, Knip, formatting, architecture guards, and real Foundation archive and Apple legacy simulator CLI/MCP verification. No real Hopper, Ghidra, or IDA verification claim.
This commit is contained in:
morluto
2026-10-10 05:56:01 +08:00
parent 077d6c407b
commit 392f1f3107
78 changed files with 1065 additions and 2020 deletions
+18 -39
View File
@@ -4,7 +4,6 @@ import { describe, expect, it } from "vitest";
import {
installLinuxHopper,
linuxHopperLauncherDigestSupported,
linuxHopperInstallDisclosure,
linuxPackageManagerCommands,
linuxSharedLibrariesAvailable,
parseLinuxDistribution,
@@ -114,44 +113,11 @@ describe("Linux Hopper installation", () => {
expect(linuxHopperLauncherDigestSupported("0".repeat(64))).toBe(false);
});
it("discloses the exact download, integrity evidence, and privileged command", () => {
expect(linuxHopperInstallDisclosure("deb", false)).toEqual({
downloadUrl:
"https://www.hopperapp.com:443/downloader/public/Hopper-6.4.2-Linux-demo.deb",
expectedBytes: 35_755_772,
expectedSha1: "e4f79dff602648a8ff4a88b773875b6bfac0dc65",
commands: [
"pkexec apt-get install -y <verified-hopper.deb> xvfb xauth python3 libx11-6 libxtst6",
],
});
});
it.each([
["deb", "apt-get"],
["rpm", "dnf"],
["arch", "pacman"],
] as const)("selects the %s native package manager", (family, executable) => {
expect(
linuxPackageManagerCommands(family, "/tmp/Hopper package", true),
).toContainEqual(
expect.objectContaining({
executable,
}),
);
expect(
linuxPackageManagerCommands(family, "/tmp/Hopper package", false),
).toContainEqual(
expect.objectContaining({
executable: "pkexec",
args: expect.arrayContaining([executable, "/tmp/Hopper package"]),
}),
);
});
it.each([
["deb", ["xvfb", "xauth", "python3", "libx11-6", "libxtst6"]],
["deb", "apt-get", ["xvfb", "xauth", "python3", "libx11-6", "libxtst6"]],
[
"rpm",
"dnf",
[
"xorg-x11-server-Xvfb",
"xorg-x11-xauth",
@@ -160,17 +126,30 @@ describe("Linux Hopper installation", () => {
"libXtst",
],
],
["arch", ["xorg-server-xvfb", "xorg-xauth", "python", "libx11", "libxtst"]],
[
"arch",
"pacman",
["xorg-server-xvfb", "xorg-xauth", "python", "libx11", "libxtst"],
],
] as const)(
"installs the %s demo-session dependencies",
(family, packages) => {
"selects the %s native package manager and dependencies",
(family, executable, packages) => {
expect(
linuxPackageManagerCommands(family, "/tmp/Hopper package", true),
).toContainEqual(
expect.objectContaining({
executable,
args: expect.arrayContaining([...packages]),
}),
);
expect(
linuxPackageManagerCommands(family, "/tmp/Hopper package", false),
).toContainEqual(
expect.objectContaining({
executable: "pkexec",
args: expect.arrayContaining([executable, "/tmp/Hopper package"]),
}),
);
},
);
+1 -17
View File
@@ -2,11 +2,7 @@ import { createHash } from "node:crypto";
import { describe, expect, it } from "vitest";
import {
installMacHopper,
macHopperInstallDisclosure,
type MacHopperInstallHost,
} from "./MacHopper.js";
import { installMacHopper, type MacHopperInstallHost } from "./MacHopper.js";
class FakeMacHopperHost implements MacHopperInstallHost {
readonly archive = new TextEncoder().encode("hopper-dmg");
@@ -75,18 +71,6 @@ class FakeMacHopperHost implements MacHopperInstallHost {
}
describe("macOS Hopper installation", () => {
it("discloses network and command boundaries before installation", () => {
expect(macHopperInstallDisclosure).toMatchObject({
networkOrigins: [
"https://www.hopperapp.com/include/files-api.php?request=releases&public=true",
"https://www.hopperapp.com:443/downloader/public/",
],
});
expect(macHopperInstallDisclosure.commands).toContain(
"hdiutil attach -readonly -nobrowse -mountpoint <private-mount> <verified-hopper.dmg>",
);
});
it("installs, verifies, opens, and cleans the official package", async () => {
const host = new FakeMacHopperHost();
await expect(installMacHopper({}, host)).resolves.toEqual({
@@ -3,27 +3,6 @@ import { expect, it } from "vitest";
import { runSetup } from "./Setup.js";
import { FakeSetupHost, options } from "./Setup.fixture.js";
it("uses the shared initial host snapshot for setup planning", async () => {
const host = new FakeSetupHost();
host.initialSetupState = async (scope) => ({
hopperPath: "/snapshot/Hopper",
providerEnvironment: { HOPPER_LAUNCHER_PATH: "/snapshot/Hopper" },
doctor: await host.doctor(scope),
});
host.clients = [{ name: "codex", configPath: "/codex.json" }];
const result = await runSetup(
{ ...options(false), dryRun: true, clientIds: ["codex"] },
host,
);
expect(result.status).toBe("planned");
expect(result.plannedActions.map(({ id }) => id)).toContain(
"configure_client:codex",
);
expect(host.doctorCalls).toBe(1);
});
it("refreshes doctor after approved setup changes", async () => {
const host = new FakeSetupHost();
host.doctorHealthy = false;
@@ -41,5 +20,4 @@ it("refreshes doctor after approved setup changes", async () => {
);
expect(result.doctor.healthy).toBe(true);
expect(host.doctorCalls).toBe(2);
});
@@ -7,6 +7,7 @@ import {
type JavaScriptArtifactGraphCoverage,
} from "./JavaScriptArtifactGraphContext.js";
import { astObservationEvidence } from "./JavaScriptArtifactGraphEvidence.js";
import { compositeKey } from "../../domain/unicodeCodePointOrder.js";
import {
addElectronInferenceEdge,
electronFindingSourceNode,
@@ -50,7 +51,9 @@ const addNativeBinding = (input: NativeBindingInput): void => {
identity: electronObservationIdentity(
context,
"javascript-requested-native-export",
`${file.path}:${value.specifier}:${value.binding_kind}:${value.members.join("\0")}:${electronRangeKey(value.location)}`,
// Members are a variable-length source-derived list: compositeKey keeps
// ["a\0b"] distinct from ["a", "b"] inside the digested identity.
`${file.path}:${value.specifier}:${value.binding_kind}:${compositeKey(value.members)}:${electronRangeKey(value.location)}`,
),
observations: [
{
@@ -31,28 +31,49 @@ const analyzeSource = async (
);
};
it.each([
"fetch('');",
"new WebSocket('');",
"navigator.serviceWorker.register('');",
"new Worker('');",
"const x = require('');",
"import y from ''; y();",
"import('');",
"localStorage.getItem('');",
"localStorage.setItem('', 1);",
"indexedDB.open('');",
"win.loadFile('');",
"win.loadURL('');",
"app.get('', handler);",
"process.on('', () => 1);",
"const { EventEmitter } = require('events'); new EventEmitter().on('', () => 1);",
"const { spawn } = require('child_process'); spawn('/bin/x').on('', () => 1);",
"const { ipcMain } = require('electron'); ipcMain.handle('', () => 1);",
"const { ipcRenderer } = require('electron'); ipcRenderer.invoke('');",
"const { contextBridge } = require('electron'); contextBridge.exposeInMainWorld('', {});",
])("analyzes the legal empty string literal in %s", async (source) => {
await expect(analyzeSource(source)).resolves.toBeDefined();
it("retains empty literal evidence across the application boundary surfaces", async () => {
const sources = [
"fetch('');",
"new WebSocket('');",
"navigator.serviceWorker.register('');",
"new Worker('');",
"const x = require('');",
"import y from ''; y();",
"import('');",
"localStorage.getItem('');",
"localStorage.setItem('', 1);",
"indexedDB.open('');",
"win.loadFile('');",
"win.loadURL('');",
"app.get('', handler);",
"process.on('', () => 1);",
"const { EventEmitter } = require('events'); new EventEmitter().on('', () => 1);",
"const { spawn } = require('child_process'); spawn('/bin/x').on('', () => 1);",
"const { ipcMain } = require('electron'); ipcMain.handle('', () => 1);",
"const { ipcRenderer } = require('electron'); ipcRenderer.invoke('');",
"const { contextBridge } = require('electron'); contextBridge.exposeInMainWorld('', {});",
];
const output = await analyzeSource(sources.join("\n"));
expect(output.graph.nodes).toEqual(
expect.arrayContaining([
expect.objectContaining({ kind: "endpoint" }),
expect.objectContaining({ kind: "worker" }),
expect.objectContaining({ kind: "ipc-channel" }),
expect.objectContaining({ kind: "context-bridge-api" }),
]),
);
expect(output.semantic_graph?.nodes).toEqual(
expect.arrayContaining([
expect.objectContaining({
kind: "request",
properties: expect.objectContaining({ endpoint: "" }),
}),
expect.objectContaining({
kind: "event",
properties: expect.objectContaining({ event_name: "" }),
}),
]),
);
});
it("analyzes a plain long-line loader without package metadata", async () => {
@@ -159,21 +159,26 @@ describe("module specifier punctuation", () => {
});
describe("ESM module URL decoding", () => {
it.each([
["./plain.mjs", "plain.mjs"],
["./space%20name.mjs", "space name.mjs"],
["./pr%C3%A9load.mjs", "préload.mjs"],
["./name%3F%23.mjs", "name?#.mjs"],
["./percent%2520.mjs?cache=1#v2", "percent%20.mjs"],
])(
"points %s imports to the file loaded by Node",
async (specifier, target) => {
const root = await createTestTempDirectory("rea-module-url-");
const main = join(root, "main.mjs");
await writeFile(
main,
`import value from ${JSON.stringify(specifier)}; console.log(value);`,
);
it("resolves URL-encoded imports to the files loaded by Node", async () => {
const cases = [
["./plain.mjs", "plain.mjs"],
["./space%20name.mjs", "space name.mjs"],
["./pr%C3%A9load.mjs", "préload.mjs"],
["./name%3F%23.mjs", "name?#.mjs"],
["./percent%2520.mjs?cache=1#v2", "percent%20.mjs"],
] as const;
const root = await createTestTempDirectory("rea-module-url-");
const main = join(root, "main.mjs");
await writeFile(
main,
cases
.map(
([specifier], index) =>
`import value${index} from ${JSON.stringify(specifier)}; console.log(value${index});`,
)
.join("\n"),
);
for (const [specifier, target] of cases) {
await writeFile(
join(root, target),
`export default ${JSON.stringify(target)};`,
@@ -181,19 +186,23 @@ describe("ESM module URL decoding", () => {
const encoded = specifier.slice(2).split("?", 1)[0]?.split("#", 1)[0];
if (encoded !== undefined && encoded !== target)
await writeFile(join(root, encoded), 'export default "encoded decoy";');
const native = await promisify(execFile)(process.execPath, [main], {
timeout: 5_000,
});
expect(native.stdout.trim()).toBe(target);
}
const native = await promisify(execFile)(process.execPath, [main], {
timeout: 5_000,
});
expect(native.stdout.trim().split("\n")).toEqual(
cases.map(([, target]) => target),
);
const result = await analyzeJavaScriptApplication({
input_path: root,
format: "directory",
});
if (!result.ok) throw result.error;
const { graph } = javascriptApplicationAnalysisResultSchema.parse(
result.value.normalized_result,
);
const result = await analyzeJavaScriptApplication({
input_path: root,
format: "directory",
});
if (!result.ok) throw result.error;
const { graph } = javascriptApplicationAnalysisResultSchema.parse(
result.value.normalized_result,
);
for (const [specifier, target] of cases) {
const imports = graph.edges.filter(
(edge) =>
edge.relation === "imports" &&
@@ -202,8 +211,8 @@ describe("ESM module URL decoding", () => {
expect(imports.length).toBeGreaterThan(0);
for (const edge of imports)
expect(edge.properties.resolved_path).toBe(target);
},
);
}
});
it("preserves CommonJS literal percent names", () => {
expect(
@@ -249,26 +258,21 @@ const packageEntryUrlCases = [
["main", "./actual#file.cjs", "actual#file.cjs"],
] as const;
describe("package exports URL paths", () => {
it.each(
(["import", "require"] as const).flatMap((moduleKind) =>
packageEntryUrlCases.map(([field, declaredPath, target]) => ({
moduleKind,
field,
declaredPath,
target,
})),
),
)(
"matches Node $moduleKind for $field $declaredPath",
async ({ moduleKind, field, declaredPath, target }) => {
const root = await createTestTempDirectory("rea-package-export-url-");
const packageRoot = join(root, "node_modules", "fixture");
it.each(["import", "require"] as const)(
"matches Node %s across package exports and main path representations",
async (moduleKind) => {
const root = await createTestTempDirectory("rea-package-export-url-");
for (const [
index,
[field, declaredPath, target],
] of packageEntryUrlCases.entries()) {
const name = `fixture-${index}`;
const packageRoot = join(root, "node_modules", name);
await mkdir(packageRoot, { recursive: true });
await writeFile(
join(packageRoot, "package.json"),
JSON.stringify({
name: "fixture",
name,
[field]: declaredPath,
}),
);
@@ -282,41 +286,54 @@ describe("package exports URL paths", () => {
join(packageRoot, literal),
'module.exports="literal decoy";',
);
const main = join(
root,
moduleKind === "import" ? "main.mjs" : "main.cjs",
);
await writeFile(
main,
moduleKind === "import"
? 'import value from "fixture"; console.log(value);'
: 'console.log(require("fixture"));',
);
const native = await promisify(execFile)(process.execPath, [main], {
timeout: 5_000,
});
expect(native.stdout.trim()).toBe(target);
const result = await analyzeJavaScriptApplication({
input_path: root,
format: "directory",
});
if (!result.ok) throw result.error;
const { graph } = javascriptApplicationAnalysisResultSchema.parse(
result.value.normalized_result,
);
}
const main = join(root, moduleKind === "import" ? "main.mjs" : "main.cjs");
await writeFile(
main,
packageEntryUrlCases
.map((_, index) =>
moduleKind === "import"
? `import value${index} from "fixture-${index}"; console.log(value${index});`
: `console.log(require("fixture-${index}"));`,
)
.join("\n"),
);
const native = await promisify(execFile)(process.execPath, [main], {
timeout: 5_000,
});
expect(native.stdout.trim().split("\n")).toEqual(
packageEntryUrlCases.map(([, , target]) => target),
);
const result = await analyzeJavaScriptApplication({
input_path: root,
format: "directory",
});
if (!result.ok) throw result.error;
const { graph } = javascriptApplicationAnalysisResultSchema.parse(
result.value.normalized_result,
);
for (const [
index,
[field, declaredPath, target],
] of packageEntryUrlCases.entries()) {
const imports = graph.edges.filter(
(edge) =>
edge.relation === "imports" &&
edge.properties.specifier === "fixture",
edge.properties.specifier === `fixture-${index}`,
);
expect(imports.length).toBeGreaterThan(0);
expect(
imports.length,
`${moduleKind}: ${field} ${declaredPath}`,
).toBeGreaterThan(0);
for (const edge of imports)
expect(edge.properties.resolved_path).toBe(
`node_modules/fixture/${target}`,
`node_modules/fixture-${index}/${target}`,
);
},
);
}
},
);
describe("package exports URL path rejections", () => {
it.each(
(["import", "require"] as const).flatMap((moduleKind) =>
[
@@ -1,5 +1,3 @@
import { createHash } from "node:crypto";
import { describe, expect, it } from "vitest";
import { MANAGED_RECONSTRUCTION_IMPORT_EXAMPLE } from "../../contracts/managed/managedWorkflowExamples.js";
@@ -24,50 +22,6 @@ const exampleMethod = () => {
};
describe("managed decompiler reconstruction import", () => {
it("imports decompiler output as inference locked to static IL evidence", () => {
const result = importManagedReconstruction(exampleInput());
expect(result).toMatchObject({
phase: "reconstruction-import",
executed: false,
static_observation: {
artifact_sha256: "2".repeat(64),
mvid: "11112222-3333-4444-9555-666677778888",
},
decompiler: {
name: "ilspycmd",
version: "9.1.0.7988",
family: "ilspy",
},
summary: {
imported_methods: 1,
decompiled_csharp_methods: 1,
},
methods: [
{
token: "0x06000001",
signature_sha256: "3".repeat(64),
normalized_il_sha256: "5".repeat(64),
validation: {
matched_static_member: true,
exact_build_required: true,
canonical_observation: false,
confidence_floor: "inference",
},
},
],
});
expect(result.reconstruction_id).toMatch(/^mre_[a-f0-9]{64}$/u);
expect(result.methods[0]?.reconstruction.text_sha256).toBe(
createHash("sha256")
.update("internal static void Main() { }")
.digest("hex"),
);
expect(result.limitations.join(" ")).toContain(
"metadata and IL observations remain canonical",
);
});
it("rejects reconstruction text hash drift", () => {
expect(() =>
importManagedReconstruction({
@@ -147,29 +101,6 @@ describe("managed decompiler reconstruction import", () => {
}),
).toThrow(/does not match/u);
});
it("wraps imported reconstruction in Evidence", () => {
const evidence = importManagedReconstructionEvidence(exampleInput());
if (!evidence.ok) throw evidence.error;
expect(evidence.value).toMatchObject({
operation: "import_managed_reconstruction",
provider: { id: "rea-dotnet-workflows" },
confidence: "inferred",
authority: "analyst-inference",
normalized_result: {
phase: "reconstruction-import",
methods: [
{
reconstruction: {
kind: "decompiled-csharp",
language: "csharp",
},
},
],
},
});
});
});
describe("managed reconstruction input diagnostics", () => {
@@ -71,31 +71,6 @@ describe("native API switch uncertainty", () => {
});
describe("native API inspection", () => {
it("preserves structured type and jump-table boundary evidence", () => {
const dossier = functionDossierSchema.parse(ghidraFunctionDossier());
expect(projectNativeApiInspection(dossier)).toMatchObject({
procedure: { address: "0x401000", name: "fixture_main" },
boundary: {
available: true,
return_type: { data_type: "int", confidence: "medium" },
jump_tables: [
{
dispatch_address: "0x401010",
data_sources: [{ address: "0x403000" }],
mappings: [
{
target_address: "0x401020",
},
],
},
],
},
unsupported_branches: [],
residual_unknowns: [],
});
});
it("preserves unsupported provider branches as residual unknowns", () => {
const value = ghidraFunctionDossier();
if (typeof value !== "object" || value === null || Array.isArray(value))