test: classify filesystem and process workflows by boundary

Move artifact inventory, application projection, runtime reconciliation, and TODO scanner suites into their real boundary lanes. Extract Hopper process/socket cleanup cases while keeping injected session cleanup cases in composition.

Validation: all 56 focused tests passed; discovery finds all 876 test files exactly once. Test assertions and provider verification scope are unchanged.
This commit is contained in:
morluto
2026-10-12 04:44:13 +08:00
parent 12fa8fd9f9
commit c2b56e3e1c
8 changed files with 193 additions and 193 deletions
@@ -1,310 +0,0 @@
import { mkdir, symlink, writeFile } from "node:fs/promises";
import { dirname, join } from "node:path";
import {
TextReader,
Uint8ArrayReader,
Uint8ArrayWriter,
ZipWriter,
} from "@zip.js/zip.js";
import { describe, expect, it } from "vitest";
import { fragmentInventoryEvidence } from "../../fixtures/artifactEvidence.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import {
createNonApplicationZipInventory,
requireSuccessfulProjection,
} from "../../support/applicationSessionFixture.js";
import { projectAppleApplicationEvidence } from "../../../src/application/apple/AppleApplicationService.js";
import { createDirectAnalysis } from "../../../src/composition/directAnalysis.js";
import { thinMach } from "../../../src/domain/binaryTarget.fixture.js";
import { appleApplicationProjectionResultSchema } from "../../../src/domain/apple/appleApplication.js";
import { parseEvidence } from "../../../src/domain/evidence.js";
const { runProviderAnalysis } = createDirectAnalysis({});
// Real ZIP entries cross the former component and bridge-candidate limits.
const FRAMEWORK_COUNT = 250;
const SCRIPT_COUNT = 40;
const NATIVE_COUNT = 40;
async function createCompleteAppleProjection() {
const root = await createTestTempDirectory("rea-apple-complete-");
const path = join(root, "Complete.ipa");
const writer = new ZipWriter(new Uint8ArrayWriter());
for (let index = 0; index < FRAMEWORK_COUNT; index++) {
const name = String(index).padStart(4, "0");
await writer.add(
`Payload/Complete.app/Frameworks/F${name}.framework/Info.plist`,
new TextReader("<plist><dict/></plist>"),
);
}
for (let index = 0; index < SCRIPT_COUNT; index++) {
await writer.add(
`Payload/Complete.app/script-${String(index).padStart(3, "0")}.js`,
new TextReader("bridge.call();"),
);
}
for (let index = 0; index < NATIVE_COUNT; index++) {
await writer.add(
`Payload/Complete.app/Frameworks/Native${String(index).padStart(3, "0")}.dylib`,
new Uint8ArrayReader(
Uint8Array.from([0xcf, 0xfa, 0xed, 0xfe, 0x0c, 0, 0, 1]),
),
);
}
await writeFile(path, await writer.close());
const inventory = parseEvidence(
await runProviderAnalysis(path, "inventory_artifact", {}),
);
const fragments = fragmentInventoryEvidence(inventory, 3);
const result = projectAppleApplicationEvidence({
inventory_evidence: fragments,
});
if (!result.ok) throw new TypeError("Could not project fixture inventory");
const projection = appleApplicationProjectionResultSchema.parse(
result.value.normalized_result,
);
expect([...projection.source_evidence_ids].sort()).toEqual(
fragments.map(({ evidence_id }) => evidence_id).sort(),
);
return projection;
}
describe("Apple application projection", () => {
it("projects deterministic IPA components and bridge hypotheses from exact inventory Evidence", async () => {
const root = await createTestTempDirectory("rea-apple-");
const path = join(root, "Fixture.ipa");
const writer = new ZipWriter(new Uint8ArrayWriter());
await writer.add("Payload/Fixture.app/", undefined, { directory: true });
await writer.add(
"Payload/Fixture.app/Info.plist",
new TextReader("<plist><dict/></plist>"),
);
await writer.add(
"Payload/Fixture.app/Fixture",
new Uint8ArrayReader(
Uint8Array.from([0xcf, 0xfa, 0xed, 0xfe, 0x0c, 0, 0, 1]),
),
);
await writer.add(
"Payload/Fixture.app/Frameworks/React.framework/React",
new Uint8ArrayReader(
Uint8Array.from([0xcf, 0xfa, 0xed, 0xfe, 0x0c, 0, 0, 1]),
),
);
await writer.add(
"Payload/Fixture.app/main.js",
new TextReader("bridge.call();"),
);
await writer.add(
"Payload/Fixture.app/embedded.mobileprovision",
new TextReader("opaque signing bytes"),
);
await writeFile(path, await writer.close());
const inventory = parseEvidence(
await runProviderAnalysis(path, "inventory_artifact", {}),
);
const first = projectAppleApplicationEvidence({
inventory_evidence: [inventory],
});
const second = projectAppleApplicationEvidence({
inventory_evidence: [inventory],
});
const left = appleApplicationProjectionResultSchema.parse(
requireSuccessfulProjection(first).normalized_result,
);
const right = appleApplicationProjectionResultSchema.parse(
requireSuccessfulProjection(second).normalized_result,
);
expect(left).toEqual(right);
expect(left).toMatchObject({
root_format: "ipa",
application_roots: ["Payload/Fixture.app"],
coverage: {
status: "complete-within-inventory",
inventory_complete: true,
},
});
expect(left.components.bundle_metadata).toHaveLength(1);
expect(left.components.executables.length).toBeGreaterThanOrEqual(2);
expect(left.components.frameworks).toHaveLength(1);
expect(left.components.javascript).toHaveLength(1);
expect(left.components.signing).toHaveLength(1);
expect(left.runtime_families).toEqual(
expect.arrayContaining(["javascript", "native", "react-native"]),
);
expect(left.bridge_candidates).toEqual([
expect.objectContaining({
basis: "javascript-and-native-content",
native_path: "Payload/Fixture.app/Fixture",
}),
expect.objectContaining({
basis: "react-native-convention",
native_path: "Payload/Fixture.app/Frameworks/React.framework/React",
}),
]);
expect(JSON.stringify(left)).not.toContain("opaque signing bytes");
});
it("reports a ZIP without an application bundle instead of guessing one", async () => {
const inventory =
await createNonApplicationZipInventory("rea-apple-empty-");
const projection = appleApplicationProjectionResultSchema.parse(
requireSuccessfulProjection(
projectAppleApplicationEvidence({ inventory_evidence: [inventory] }),
).normalized_result,
);
expect(projection).toMatchObject({
root_format: "zip",
application_roots: [],
bundles: [],
});
expect(projection.limitations).toContain(
"No application bundle (Payload/*.app or *.app/Contents) was present in the supplied inventory pages.",
);
});
it("rejects inventories of non-Apple package formats", async () => {
const root = await createTestTempDirectory("rea-apple-invalid-");
const path = join(root, "fixture.apk");
const writer = new ZipWriter(new Uint8ArrayWriter());
await writer.add("AndroidManifest.xml", new TextReader("<manifest/>"));
await writeFile(path, await writer.close());
const inventory = parseEvidence(
await runProviderAnalysis(path, "inventory_artifact", {}),
);
expect(
projectAppleApplicationEvidence({ inventory_evidence: [inventory] }),
).toMatchObject({
ok: false,
error: { _tag: "AnalysisInputError" },
});
});
});
describe("macOS application projection", () => {
it("projects a macOS .app directory inventory with nested bundle roles", async () => {
const root = await createTestTempDirectory("rea-apple-macos-");
const app = join(root, "Fixture.app");
// A complete thin arm64 header, as target admission requires.
const machO = thinMach(0xcffaedfe, 0x0100000c);
const files: [string, string | Uint8Array][] = [
[
"Contents/Info.plist",
"<plist><dict><key>CFBundleExecutable</key><string>Fixture</string></dict></plist>",
],
["Contents/MacOS/Fixture", machO],
["Contents/XPCServices/Fetch.xpc/Contents/MacOS/Fetch", machO],
["Contents/PlugIns/Share.appex/Contents/MacOS/Share", machO],
["Contents/Library/LoginItems/Login.app/Contents/MacOS/Login", machO],
["Contents/Library/LaunchServices/com.example.helper", machO],
[
"Contents/Library/LaunchDaemons/com.example.helper.plist",
"<plist><dict/></plist>",
],
["Contents/Frameworks/Core.framework/Versions/A/Core", machO],
];
for (const [relative, content] of files) {
await mkdir(dirname(join(app, relative)), { recursive: true });
await writeFile(join(app, relative), content);
}
await symlink(
"A",
join(app, "Contents/Frameworks/Core.framework/Versions/Current"),
);
const inventory = parseEvidence(
await runProviderAnalysis(app, "inventory_artifact", {}),
);
const result = projectAppleApplicationEvidence({
inventory_evidence: [inventory],
});
const projection = appleApplicationProjectionResultSchema.parse(
requireSuccessfulProjection(result).normalized_result,
);
expect(requireSuccessfulProjection(result).subject?.format).toBe(
"directory",
);
expect(projection).toMatchObject({
root_format: "directory",
platforms: ["macos"],
application_roots: ["."],
symlinks: ["Contents/Frameworks/Core.framework/Versions/Current"],
coverage: { status: "complete-within-inventory" },
});
expect(projection.bundles.map(({ path, role }) => [path, role])).toEqual([
[".", "application"],
["Contents/Frameworks/Core.framework", "framework"],
["Contents/Library/LoginItems/Login.app", "login-item"],
["Contents/PlugIns/Share.appex", "app-extension"],
["Contents/XPCServices/Fetch.xpc", "xpc-service"],
]);
expect(
projection.components.privileged_helpers.map(({ path }) => path),
).toEqual(["Contents/Library/LaunchServices/com.example.helper"]);
expect(projection.components.launchd_plists).toEqual([
expect.objectContaining({
path: "Contents/Library/LaunchDaemons/com.example.helper.plist",
domain: "daemon",
}),
]);
});
});
describe("Apple application projection completeness", () => {
it("returns every component and bridge hypothesis from fragments of a real ZIP inventory", async () => {
const projection = await createCompleteAppleProjection();
expect(projection.components.frameworks).toHaveLength(FRAMEWORK_COUNT);
expect(projection.components.bundle_metadata).toHaveLength(FRAMEWORK_COUNT);
expect(projection.components.javascript).toHaveLength(SCRIPT_COUNT);
expect(projection.components.native_libraries).toHaveLength(NATIVE_COUNT);
expect(projection.source_evidence_ids).toHaveLength(3);
expect(new Set(projection.source_evidence_ids).size).toBe(3);
// One candidate per script/native pair. Deriving this catches a pairing
// regression, which the previous literal 10_201 could not.
expect(projection.bridge_candidates).toHaveLength(
SCRIPT_COUNT * NATIVE_COUNT,
);
expect(projection.coverage).toEqual({
status: "complete-within-inventory",
inventory_complete: true,
});
expect(projection).not.toHaveProperty("omitted_components");
expect(projection).not.toHaveProperty("omitted_bridge_candidates");
});
it("retains long ZIP application roots when the IPA omits directory entries", async () => {
const root = await createTestTempDirectory("rea-apple-root-");
const path = join(root, "Fixture.ipa");
const applicationRoot = `Payload/${"LongApp".repeat(750)}.app`;
const writer = new ZipWriter(new Uint8ArrayWriter());
await writer.add(
`${applicationRoot}/Fixture`,
new Uint8ArrayReader(
Uint8Array.from([0xcf, 0xfa, 0xed, 0xfe, 0x0c, 0, 0, 1]),
),
);
await writeFile(path, await writer.close());
const inventory = parseEvidence(
await runProviderAnalysis(path, "inventory_artifact", {}),
);
const result = projectAppleApplicationEvidence({
inventory_evidence: [inventory],
});
if (!result.ok) throw result.error;
expect(
appleApplicationProjectionResultSchema.parse(
result.value.normalized_result,
),
).toMatchObject({
application_roots: [applicationRoot],
components: { executables: [expect.any(Object)] },
});
});
});
@@ -1,265 +0,0 @@
import { mkdir, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { fragmentInventoryEvidence } from "../../fixtures/artifactEvidence.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { inventoryArtifact } from "../../fixtures/artifactInventory.js";
import { artifactInventoryResultSchema } from "../../../src/domain/artifactGraph.js";
import {
artifactComparisonResultSchema,
compareArtifacts,
} from "../../../src/domain/artifactComparison.js";
import { createEvidence } from "../../../src/domain/evidence.js";
import { jsonValueSchema } from "../../../src/domain/jsonValue.js";
const PROVIDER = {
id: "rea-artifact-graph",
name: "REA artifact graph",
version: "1",
} as const;
const observe = async (path: string) => {
const inventory = await inventoryArtifact(path);
return createEvidence(
{
path,
sha256: inventory.manifest.root_sha256,
format: inventory.manifest.root_format,
},
PROVIDER,
{
operation: "inventory_artifact",
parameters: {},
result: jsonValueSchema.parse(inventory),
confidence: "observed",
authority: "shipped-artifact",
},
);
};
const changedArtifactComparison = async () => {
const parent = await createTestTempDirectory("rea-artifact-compare-");
const leftPath = join(parent, "left.app");
const rightPath = join(parent, "right.app");
await Promise.all([mkdir(leftPath), mkdir(rightPath)]);
await Promise.all([
writeFile(join(leftPath, "main.js"), "old();"),
writeFile(join(leftPath, "same.txt"), "same"),
writeFile(join(rightPath, "main.js"), "newer();"),
writeFile(join(rightPath, "same.txt"), "same"),
writeFile(join(rightPath, "added.txt"), "added"),
]);
const left = await observe(leftPath);
const right = await observe(rightPath);
return {
left,
right,
result: compareArtifacts(left, right),
};
};
describe("artifact comparison", () => {
it("classifies deterministic path changes and cites both inventories", async () => {
const firstObservation = await changedArtifactComparison();
const secondObservation = await changedArtifactComparison();
const first = firstObservation.result;
const second = secondObservation.result;
expect(first).toEqual(second);
expect(artifactComparisonResultSchema.parse(first)).toMatchObject({
status: "changed",
summary: { added: 1, changed: 2, unknown: 0 },
changes: expect.arrayContaining([
expect.objectContaining({ logical_path: "added.txt" }),
]),
});
expect(first.changes[0]?.evidence_links).toEqual([
firstObservation.left.evidence_id,
firstObservation.right.evidence_id,
]);
expect(first.changes).toEqual(
expect.arrayContaining([
expect.objectContaining({
logical_path: "added.txt",
classification: "added",
}),
expect.objectContaining({
logical_path: "main.js",
classification: "changed",
dimensions: expect.arrayContaining(["content", "size"]),
}),
]),
);
});
it("reports incomplete inventory as truncated, never unchanged", async () => {
const root = await createTestTempDirectory("rea-artifact-truncated-");
await writeFile(join(root, "one.txt"), "one");
const complete = await observe(root);
const completeInventory = artifactInventoryResultSchema.parse(
complete.normalized_result,
);
const incomplete = createEvidence(
{
path: root,
sha256: complete.subject?.digest.sha256 ?? "0".repeat(64),
format: "directory",
},
PROVIDER,
{
operation: "inventory_artifact",
parameters: {},
result: jsonValueSchema.parse({
...completeInventory,
nodes: [],
}),
confidence: "observed",
authority: "shipped-artifact",
limitations: ["Inventory node observations are unavailable."],
},
);
const comparison = compareArtifacts(incomplete, incomplete);
expect(comparison).toMatchObject({
status: "truncated",
summary: { unchanged: 0, unknown: 2 },
});
expect(comparison.limitations).toContain(
"Left artifact inventory is incomplete.",
);
});
});
describe("artifact comparison completeness", () => {
it("compares every graph member for inventories larger than 500 entries", async () => {
const root = await createTestTempDirectory("rea-artifact-pages-");
const entryCount = 501;
await Promise.all(
Array.from({ length: entryCount }, async (_, index) =>
writeFile(
join(root, `file-${String(index).padStart(3, "0")}.txt`),
String(index),
),
),
);
const complete = await observe(root);
const graph = artifactInventoryResultSchema.parse(
complete.normalized_result,
);
// The real risk above 500 entries is silent truncation, so assert the
// manifest counts reconcile with the arrays actually returned and that
// every written file is present. Deriving from `entryCount` keeps this
// valid at any size instead of freezing a page boundary.
expect(graph.manifest.node_count).toBe(graph.nodes.length);
expect(graph.manifest.occurrence_count).toBe(graph.occurrences.length);
expect(graph.manifest.edge_count).toBe(graph.edges.length);
const written = new Set(
Array.from(
{ length: entryCount },
(_, index) => `file-${String(index).padStart(3, "0")}.txt`,
),
);
// Occurrences carry the inventory paths, so completeness is checked there.
const paths = new Set(
graph.occurrences.map((occurrence) => occurrence.logical_path),
);
expect([...written].filter((path) => !paths.has(path))).toEqual([]);
expect(
graph.occurrences.filter(
(occurrence) => occurrence.entry_kind === "file",
),
).toHaveLength(entryCount);
expect(compareArtifacts(complete, complete)).toMatchObject({
status: "unchanged",
summary: { unchanged: 502, unknown: 0 },
changes: [],
});
}, 15_000);
it("assembles real inventory fragments and retains every citation", async () => {
const parent = await createTestTempDirectory("rea-artifact-fragments-");
const leftPath = join(parent, "left.app");
const rightPath = join(parent, "right.app");
await Promise.all([mkdir(leftPath), mkdir(rightPath)]);
// Cross the former 100-citation limit with distinct, real graph members.
const fragmentCount = 101;
await Promise.all(
Array.from({ length: fragmentCount }, async (_, index) => {
await Promise.all([
writeFile(join(leftPath, `file-${index}.js`), `left(${index});`),
writeFile(join(rightPath, `file-${index}.js`), `right(${index});`),
]);
}),
);
const left = await observe(leftPath);
const right = await observe(rightPath);
const leftFragments = fragmentInventoryEvidence(left, fragmentCount);
const rightFragments = fragmentInventoryEvidence(right, fragmentCount);
const citations = [...leftFragments, ...rightFragments]
.map(({ evidence_id }) => evidence_id)
.sort();
expect(new Set(citations).size).toBe(fragmentCount * 2);
const comparison = compareArtifacts(leftFragments, rightFragments);
const complete = compareArtifacts(left, right);
expect(
comparison.changes
.filter(({ logical_path }) => logical_path !== ".")
.map(({ logical_path, classification }) => ({
logical_path,
classification,
}))
.sort((left, right) =>
left.logical_path.localeCompare(right.logical_path),
),
).toEqual(
Array.from({ length: fragmentCount }, (_, index) => ({
logical_path: `file-${index}.js`,
classification: "changed",
})).sort((left, right) =>
left.logical_path.localeCompare(right.logical_path),
),
);
expect({
...comparison,
changes: comparison.changes.map((change) => ({
...change,
evidence_links: [...change.evidence_links].sort(),
})),
}).toEqual({
...complete,
changes: complete.changes.map((change) => ({
...change,
evidence_links: citations,
})),
});
}, 15_000);
it("rejects non-inventory and tampered Evidence", async () => {
const root = await createTestTempDirectory("rea-artifact-invalid-");
const evidence = await observe(root);
expect(() =>
compareArtifacts({ ...evidence, operation: "binary_overview" }, evidence),
).toThrow(/identifier/u);
const wrongOperation = createEvidence(undefined, PROVIDER, {
operation: "binary_overview",
parameters: {},
result: evidence.normalized_result,
});
expect(() => compareArtifacts(wrongOperation, evidence)).toThrow(
/inspect_artifact/u,
);
const mismatchedSubject = createEvidence(
{ path: root, sha256: "f".repeat(64), format: "directory" },
PROVIDER,
{
operation: "inventory_artifact",
parameters: {},
result: evidence.normalized_result,
},
);
expect(() => compareArtifacts(mismatchedSubject, evidence)).toThrow(
/root digest/u,
);
});
});
@@ -1,34 +1,12 @@
import {
access,
mkdir,
mkdtemp,
readFile,
rm,
writeFile,
} from "node:fs/promises";
import { access, mkdir, readFile, rm, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect, it, onTestFinished } from "vitest";
import {
createAnalysisExecution,
type AnalysisClient,
} from "../../../src/application/AnalysisProvider.js";
import type { AnalysisClient } from "../../../src/application/AnalysisProvider.js";
import { HopperStartError } from "../../../src/domain/hopperErrors.js";
import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js";
import { ProviderCleanupError } from "../../../src/domain/providerCleanupError.js";
import { err, ok as resultOk } from "../../../src/domain/result.js";
import type {
BridgeLauncher,
BridgeSession,
} from "../../../src/hopper/BridgeLauncher.js";
import { HopperClient } from "../../../src/hopper/HopperClient.js";
import {
acquireHopperTargetLease,
type HopperTargetLease,
} from "../../../src/hopper/HopperTargetLease.js";
import { cleanupOwnedProcessGroup } from "../../../src/process/ProcessOwnership.js";
import { spawnOwnedProviderProcess } from "../../../src/process/ProviderProcess.js";
import { hopperFixturePath } from "../../boundary/providers/hopper/hopperClient.fixture.js";
import { observed as ok } from "../../fixtures/analysisExecution.js";
import {
createBinarySessionTargets,
@@ -289,147 +267,3 @@ it("does not start a replacement cancelled while pending cleanup completes", asy
expect(created).toBe(1);
await expect(access(runtime)).rejects.toMatchObject({ code: "ENOENT" });
});
class RetryingHopperLauncher implements BridgeLauncher {
cleanupAllowed = false;
cleanupAttempts = 0;
directory: string | undefined;
lease: HopperTargetLease | undefined;
constructor(
readonly leaseDirectory: string,
readonly targetPath: string,
readonly cleanupRequired = false,
) {}
acquire(runId: string) {
return acquireHopperTargetLease({
targetPath: this.targetPath,
targetKind: "database",
loaderArgs: [],
runId,
directory: this.leaseDirectory,
});
}
async launch(session: BridgeSession) {
const lease = await this.acquire(session.runId);
if (!lease.acquired)
return err(
new HopperStartError({ userMessage: "fixture lease is held" }),
);
this.lease = lease.lease;
this.directory = session.directory;
const started = await spawnOwnedProviderProcess({
command: process.execPath,
arguments: [
hopperFixturePath,
session.socketPath,
session.token,
session.runId,
this.cleanupRequired ? "cleanup-required" : "acknowledge",
],
runId: session.runId,
expectedCommand: null,
});
return resultOk({
...started,
ownsProcessLifetime: true as const,
providerLifetime: "launcher-process" as const,
shutdownMode: "process-cleanup" as const,
cleanup: () => {
this.cleanupAttempts += 1;
return this.cleanupAllowed
? cleanupOwnedProcessGroup(started.ownership)
: Promise.resolve({
cleaned: false as const,
reason: "fixture process cleanup not confirmed",
});
},
releaseLease: () => lease.lease.release(),
});
}
}
it("retains Hopper process handles, private files, and lease until an actual session cleanup retry succeeds", async () => {
const leaseDirectory = await mkdtemp("/tmp/rea-hl-");
onTestFinished(() => rm(leaseDirectory, { recursive: true, force: true }));
const [first, second] = await createBinarySessionTargets();
const launcher = new RetryingHopperLauncher(leaseDirectory, first);
const hopper = new HopperClient({ launcher, startupTimeoutMs: 10_000 });
let clientsCreated = 0;
const session = createTestBinarySession(() => {
clientsCreated += 1;
return {
execute: async () => {
const started = await hopper.start();
return started.ok
? resultOk(
createAnalysisExecution(null, {
id: "hopper",
name: "fixture Hopper",
version: null,
}),
)
: started;
},
close: (options) => hopper.close(options),
};
});
onTestFinished(async () => {
launcher.cleanupAllowed = true;
await session.close();
await hopper.close();
await launcher.lease?.release();
});
expect(await session.open(first)).toMatchObject({ ok: true });
expect(await session.close()).toMatchObject({
ok: false,
error: { cleanupIncomplete: true },
});
const runtime = launcher.directory;
if (runtime === undefined)
throw new Error("Fixture did not capture its runtime");
await access(runtime);
expect(launcher.cleanupAttempts).toBe(1);
expect(await launcher.acquire("other-owner")).toMatchObject({
acquired: false,
});
expect(await session.open(second)).toMatchObject({
ok: false,
error: { cleanupIncomplete: true },
});
expect(clientsCreated).toBe(1);
expect(launcher.cleanupAttempts).toBe(2);
launcher.cleanupAllowed = true;
expect(await session.close()).toEqual(resultOk(null));
expect(launcher.cleanupAttempts).toBe(3);
await expect(access(runtime)).rejects.toMatchObject({ code: "ENOENT" });
const replacement = await launcher.acquire("replacement-owner");
expect(replacement.acquired).toBe(true);
if (replacement.acquired) await replacement.lease.release();
expect((await session.open(second)).ok).toBe(true);
expect(clientsCreated).toBe(2);
});
it("reports a direct Hopper close failure and retries the retained owned process", async () => {
const leaseDirectory = await mkdtemp("/tmp/rea-hl-");
onTestFinished(() => rm(leaseDirectory, { recursive: true, force: true }));
const [target] = await createBinarySessionTargets();
const launcher = new RetryingHopperLauncher(leaseDirectory, target, true);
const hopper = new HopperClient({ launcher, startupTimeoutMs: 10_000 });
onTestFinished(async () => {
launcher.cleanupAllowed = true;
await hopper.close();
await launcher.lease?.release();
});
expect(await hopper.start()).toMatchObject({ ok: true });
expect(await hopper.close()).toMatchObject({
ok: false,
error: { cleanupIncomplete: true },
});
expect(launcher.cleanupAttempts).toBe(1);
launcher.cleanupAllowed = true;
expect(await hopper.close()).toEqual(resultOk(null));
expect(launcher.cleanupAttempts).toBe(2);
});
@@ -1,330 +0,0 @@
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import {
TextReader,
Uint8ArrayReader,
Uint8ArrayWriter,
ZipWriter,
} from "@zip.js/zip.js";
import { describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import {
createNonApplicationZipInventory,
requireSuccessfulProjection,
} from "../../support/applicationSessionFixture.js";
import { projectAndroidApplicationEvidence } from "../../../src/application/android/AndroidApplicationService.js";
import { createDirectAnalysis } from "../../../src/composition/directAnalysis.js";
import { androidApplicationProjectionResultSchema } from "../../../src/domain/android/androidApplication.js";
import { parseEvidence } from "../../../src/domain/evidence.js";
const { runProviderAnalysis } = createDirectAnalysis({});
describe("Android application projection", () => {
it("projects deterministic APK components and explicit bridge hypotheses", async () => {
const root = await createTestTempDirectory("rea-android-");
const path = join(root, "Fixture.apk");
const writer = new ZipWriter(new Uint8ArrayWriter());
await writer.add(
"AndroidManifest.xml",
new Uint8ArrayReader(Uint8Array.from([3, 0, 8, 0])),
);
await writer.add(
"classes.dex",
new Uint8ArrayReader(
Uint8Array.from([0x64, 0x65, 0x78, 0x0a, 0x30, 0x33, 0x35, 0]),
),
);
const elf = () =>
new Uint8ArrayReader(
Uint8Array.from([0x7f, 0x45, 0x4c, 0x46, 2, 1, 1, 0]),
);
await writer.add("lib/arm64-v8a/libreactnativejni.so", elf());
await writer.add("lib/arm64-v8a/libflutter.so", elf());
await writer.add("lib/arm64-v8a/libunity.so", elf());
await writer.add("lib/arm64-v8a/libcommunity.so", elf());
await writer.add("assets/index.js", new TextReader("bridge();"));
await writer.add("META-INF/FIXTURE.RSA", new TextReader("opaque signing"));
await writeFile(path, await writer.close());
const inventory = parseEvidence(
await runProviderAnalysis(path, "inventory_artifact", {}),
);
const first = projectAndroidApplicationEvidence({
inventory_evidence: [inventory],
});
const second = projectAndroidApplicationEvidence({
inventory_evidence: [inventory],
});
const left = androidApplicationProjectionResultSchema.parse(
requireSuccessfulProjection(first).normalized_result,
);
const right = androidApplicationProjectionResultSchema.parse(
requireSuccessfulProjection(second).normalized_result,
);
expect(left).toEqual(right);
expect(left).toMatchObject({
root_format: "apk",
coverage: {
status: "complete-within-inventory",
inventory_complete: true,
},
});
expect(left.components.manifests).toHaveLength(1);
expect(left.components.dex).toHaveLength(1);
expect(left.components.native_libraries).toHaveLength(4);
expect(left.components.javascript).toHaveLength(1);
expect(left.components.signing).toHaveLength(1);
expect(left.runtime_families).toEqual(
expect.arrayContaining([
"dalvik-art",
"flutter",
"javascript",
"native",
"react-native",
"unity",
]),
);
expect(left.runtime_families).not.toContain("community");
expect(left.bridge_candidates).toEqual(
expect.arrayContaining([
expect.objectContaining({ basis: "react-native-convention" }),
expect.objectContaining({ basis: "flutter-convention" }),
expect.objectContaining({ basis: "unity-convention" }),
]),
);
const community = left.bridge_candidates.filter(({ native_path }) =>
native_path.endsWith("libcommunity.so"),
);
expect(community.length).toBeGreaterThan(0);
expect(
community.every(({ basis }) => basis === "jni-library-convention"),
).toBe(true);
expect(left.limitations).toEqual(
expect.arrayContaining([
"A bridge basis is inferred from the native path and is repeated for every managed component.",
"ZIP inventory cannot see the APK Signing Block, so an empty signing array does not mean the APK is unsigned.",
]),
);
expect(JSON.stringify(left)).not.toContain("opaque signing");
});
it("rejects non-APK inventory Evidence", async () => {
const inventory = await createNonApplicationZipInventory(
"rea-android-invalid-",
);
expect(
projectAndroidApplicationEvidence({ inventory_evidence: [inventory] }),
).toMatchObject({
ok: false,
error: {
_tag: "AnalysisInputError",
issues: [
expect.objectContaining({
message: expect.stringContaining("root format is zip"),
}),
],
},
});
});
it("keeps uppercase path-derived bytecode families distinct from byte validity", async () => {
const root = await createTestTempDirectory("rea-android-suffixes-");
const path = join(root, "Suffixes.apk");
const writer = new ZipWriter(new Uint8ArrayWriter());
for (const entry of [
"classes.DEX",
"extra.dex",
"Main.CLASS",
"Other.class",
])
await writer.add(entry, new TextReader("unrecognized bytes"));
await writeFile(path, await writer.close());
const inventory = parseEvidence(
await runProviderAnalysis(path, "inventory_artifact", {}),
);
const result = projectAndroidApplicationEvidence({
inventory_evidence: [inventory],
});
const projection = androidApplicationProjectionResultSchema.parse(
requireSuccessfulProjection(result).normalized_result,
);
expect(projection.components.dex.map(({ path }) => path).sort()).toEqual([
"classes.DEX",
"extra.dex",
]);
expect(
projection.components.jvm_classes.map(({ path }) => path).sort(),
).toEqual(["Main.CLASS", "Other.class"]);
expect(
projection.components.dex.every(({ format }) => format === "file"),
).toBe(true);
expect(
projection.components.jvm_classes.every(
({ format }) => format === "file",
),
).toBe(true);
expect(projection.runtime_families).toEqual(["dalvik-art", "java-kotlin"]);
expect(projection.limitations).toContain(
"Runtime families are inferred from inventory formats and paths; filename suffixes do not establish valid DEX or JVM class bytes.",
);
});
});
describe("APK family without a root manifest", () => {
const missingManifest =
"No root AndroidManifest.xml occurrence was observed. The APK family comes from the .apk suffix of a ZIP archive, so these bytes may not be an APK.";
const projectApk = async (entries: Record<string, string>) => {
const root = await createTestTempDirectory("rea-android-manifest-");
const path = join(root, "Plain.apk");
const writer = new ZipWriter(new Uint8ArrayWriter());
for (const [entry, text] of Object.entries(entries))
await writer.add(entry, new TextReader(text));
await writeFile(path, await writer.close());
const inventory = parseEvidence(
await runProviderAnalysis(path, "inventory_artifact", {}),
);
return androidApplicationProjectionResultSchema.parse(
requireSuccessfulProjection(
projectAndroidApplicationEvidence({ inventory_evidence: [inventory] }),
).normalized_result,
);
};
it("says when the APK family rests only on the ZIP filename suffix", async () => {
expect((await projectApk({ "readme.txt": "hello" })).limitations).toContain(
missingManifest,
);
expect(
(await projectApk({ "AndroidManifest.xml": "manifest" })).limitations,
).not.toContain(missingManifest);
});
});
describe("case-distinct APK resource names", () => {
it("inventories and projects an APK whose resource names differ only in case", async () => {
const root = await createTestTempDirectory("rea-android-case-");
const path = join(root, "Shrunk.apk");
const writer = new ZipWriter(new Uint8ArrayWriter());
await writer.add(
"AndroidManifest.xml",
new Uint8ArrayReader(Uint8Array.from([3, 0, 8, 0])),
);
await writer.add(
"classes.dex",
new Uint8ArrayReader(
Uint8Array.from([0x64, 0x65, 0x78, 0x0a, 0x30, 0x33, 0x35, 0]),
),
);
await writer.add("res/2F.xml", new TextReader("upper"));
await writer.add("res/2f.xml", new TextReader("lower"));
await writeFile(path, await writer.close());
const inventory = parseEvidence(
await runProviderAnalysis(path, "inventory_artifact", {}),
);
const result = projectAndroidApplicationEvidence({
inventory_evidence: [inventory],
});
const projection = androidApplicationProjectionResultSchema.parse(
requireSuccessfulProjection(result).normalized_result,
);
expect(projection.root_format).toBe("apk");
expect(projection.components.manifests).toHaveLength(1);
expect(projection.components.dex).toHaveLength(1);
expect(JSON.stringify(inventory)).toContain("res/2F.xml");
expect(JSON.stringify(inventory)).toContain("res/2f.xml");
expect(JSON.stringify(inventory)).toContain(
"English (en-US) Unicode case folding",
);
});
});
describe("Android bridge candidate coverage", () => {
it("returns every component and bridge candidate from the inventory", async () => {
const root = await createTestTempDirectory("rea-android-complete-");
const path = join(root, "Fixture.apk");
const writer = new ZipWriter(new Uint8ArrayWriter());
const dex = Uint8Array.from([0x64, 0x65, 0x78, 0x0a, 0x30, 0x33, 0x35, 0]);
for (let index = 0; index < 1_001; index += 1)
await writer.add(
`classes${String(index).padStart(4, "0")}.dex`,
new Uint8ArrayReader(dex),
);
await writer.add("lib/arm64-v8a/libnative.so", new TextReader("native"));
await writeFile(path, await writer.close());
const inventory = parseEvidence(
await runProviderAnalysis(path, "inventory_artifact", {}),
);
const result = projectAndroidApplicationEvidence({
inventory_evidence: [inventory],
});
if (!result.ok) throw result.error;
const projection = androidApplicationProjectionResultSchema.parse(
result.value.normalized_result,
);
expect(projection.components.dex).toHaveLength(1_001);
expect(projection.bridge_candidates).toHaveLength(1_001);
expect(projection.coverage.status).toBe("complete-within-inventory");
});
it("marks a multidex by native projection partial when escaped UTF-8 candidate paths exceed its byte budget", async () => {
const root = await createTestTempDirectory("rea-android-bridge-budget-");
const path = join(root, "Large.apk");
const writer = new ZipWriter(new Uint8ArrayWriter());
const dex = Uint8Array.from([0x64, 0x65, 0x78, 0x0a, 0x30, 0x33, 0x35, 0]);
const escapedDirectory = `${"é".repeat(100)}${'"'.repeat(120)}`;
for (let index = 0; index < 129; index += 1)
await writer.add(
`${escapedDirectory}/classes${String(index + 1).padStart(3, "0")}.dex`,
new Uint8ArrayReader(dex),
);
for (let index = 0; index < 128; index += 1)
await writer.add(
`lib/arm64-v8a/libnative${String(index).padStart(3, "0")}.so`,
new TextReader("native"),
);
await writeFile(path, await writer.close());
const inventory = parseEvidence(
await runProviderAnalysis(path, "inventory_artifact", {}),
);
const result = projectAndroidApplicationEvidence({
inventory_evidence: [inventory],
});
if (!result.ok) throw result.error;
const projection = androidApplicationProjectionResultSchema.parse(
result.value.normalized_result,
);
expect(projection.components.dex).toHaveLength(129);
expect(projection.components.native_libraries).toHaveLength(128);
expect(projection.bridge_candidate_coverage).toMatchObject({
status: "partial",
total_candidates: 129 * 128,
emitted_candidates: projection.bridge_candidates.length,
omitted_candidates: 129 * 128 - projection.bridge_candidates.length,
});
expect(projection.bridge_candidates.length).toBeGreaterThan(0);
expect(projection.bridge_candidates.length).toBeLessThan(129 * 128);
expect(
Buffer.byteLength(JSON.stringify(projection.bridge_candidates)),
).toBeLessThanOrEqual(2 * 1024 * 1024);
expect(projection.coverage).toMatchObject({
status: "partial",
inventory_complete: true,
});
expect(projection.limitations).toContain(
"Bridge candidates are path-based hypotheses, not decoded JNI declarations or observed runtime calls.",
);
expect(projection.limitations).toContain(
`Bridge candidate pairs exceeded the projection safety budget; ${projection.bridge_candidate_coverage.omitted_candidates} hypotheses are omitted. Component arrays still include every component from the supplied inventory pages.`,
);
});
});
@@ -1,275 +0,0 @@
import { readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { TextReader, Uint8ArrayWriter, ZipWriter } from "@zip.js/zip.js";
import { describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import {
createNonApplicationZipInventory,
inventoryApplicationPackage,
requireDeterministicProjection,
requireSuccessfulProjection,
writeApplicationZip,
} from "../../support/applicationSessionFixture.js";
import { projectHarmonyApplicationEvidence } from "../../../src/application/harmony/HarmonyApplicationService.js";
import { createDirectAnalysis } from "../../../src/composition/directAnalysis.js";
import { harmonyApplicationProjectionResultSchema } from "../../../src/domain/harmony/harmonyApplication.js";
import { artifactInventoryResultSchema } from "../../../src/domain/artifactGraph.js";
import { parseBinaryTarget } from "../../../src/application/BinaryTargetResolver.js";
import {
ZIP_PACKAGE_FORMATS,
ZIP_NON_ENTRY_TAIL_LIMITATION,
} from "../../../src/domain/zipPackageFormat.js";
const { runProviderAnalysis } = createDirectAnalysis({});
const elf = Uint8Array.from([0x7f, 0x45, 0x4c, 0x46, 2, 1, 1, 0]);
const stageHapEntries = [
{ path: "module.json", content: '{"module":{"name":"entry"}}' },
{ path: "ets/modules.abc", content: "panda bytecode" },
{ path: "libs/arm64-v8a/libentry.so", content: elf },
{ path: "resources.index", content: "resource index" },
{ path: "resources/base/profile/main_pages.json", content: "{}" },
{ path: "assets/web/index.js", content: "bridge();" },
{ path: "META-INF/FIXTURE.p7b", content: "opaque signing" },
] as const;
describe("HarmonyOS application projection", () => {
it("projects deterministic Stage HAP components and explicit bridge hypotheses", async () => {
const path = await writeApplicationZip(
"rea-harmony-",
"Fixture.hap",
stageHapEntries,
);
const inventory = await inventoryApplicationPackage(path);
expect(inventory.subject?.format).toBe("hap");
const left = requireDeterministicProjection(
projectHarmonyApplicationEvidence,
inventory,
harmonyApplicationProjectionResultSchema,
);
expect(left).toMatchObject({
root_format: "hap",
packaging_model: "stage",
coverage: {
status: "complete-within-inventory",
inventory_complete: true,
},
});
expect(left.components.manifests.map(({ path }) => path)).toEqual([
"module.json",
]);
expect(left.components.bytecode.map(({ path }) => path)).toEqual([
"ets/modules.abc",
]);
expect(left.components.resources.map(({ path }) => path).sort()).toEqual([
"resources.index",
"resources/base/profile/main_pages.json",
]);
expect(left.components.native_libraries).toHaveLength(1);
expect(left.components.javascript).toHaveLength(1);
expect(left.components.signing).toHaveLength(1);
expect(left.runtime_families).toEqual(["ark", "javascript", "native"]);
expect(left.bridge_candidates).toEqual([
expect.objectContaining({
managed_path: "ets/modules.abc",
native_path: "libs/arm64-v8a/libentry.so",
basis: "napi-library-convention",
}),
]);
expect(left.app_pack_children).toEqual([]);
expect(JSON.stringify(left)).not.toContain("opaque signing");
expect(left.limitations).toContain(
"Manifest, module, resource, and signing semantics require a dedicated HarmonyOS provider; this projection reports exact inventory paths and hashes only.",
);
});
it("projects App Pack children by path without recursive inventory", async () => {
const entryHap = await writeApplicationZip(
"rea-harmony-entry-",
"entry.hap",
[
{ path: "module.json", content: '{"module":{}}' },
{ path: "ets/modules.abc", content: "panda" },
],
);
const featureHsp = await writeApplicationZip(
"rea-harmony-feature-",
"feature.hsp",
[{ path: "module.json", content: '{"module":{}}' }],
);
const path = await writeApplicationZip("rea-harmony-app-", "Bundle.app", [
{ path: "pack.info", content: '{"packages":[]}' },
{ path: "entry.hap", content: new Uint8Array(await readFile(entryHap)) },
{
path: "feature.hsp",
content: new Uint8Array(await readFile(featureHsp)),
},
]);
const inventory = await inventoryApplicationPackage(path);
expect(inventory.subject?.format).toBe("app-pack");
const projection = requireDeterministicProjection(
projectHarmonyApplicationEvidence,
inventory,
harmonyApplicationProjectionResultSchema,
);
expect(projection.root_format).toBe("app-pack");
expect(projection.components.manifests.map(({ path }) => path)).toEqual([
"pack.info",
]);
expect(projection.app_pack_children.map(({ path }) => path).sort()).toEqual(
["entry.hap", "feature.hsp"],
);
expect(projection.packaging_model).toBe("unknown");
expect(projection.limitations).toContain(
"App Pack child packages are listed by inventory path only; their contents are not recursively inventoried by this projection.",
);
});
});
describe("HarmonyOS packaging boundaries", () => {
it("keeps a nested .app ZIP member inside an IPA out of the App Pack classification", async () => {
const nested = await writeApplicationZip(
"rea-harmony-nested-",
"Nested.app",
[{ path: "inner.txt", content: "not an app pack" }],
);
const path = await writeApplicationZip("rea-harmony-ipa-", "Fixture.ipa", [
{ path: "Payload/App.app/Info.plist", content: "plist" },
{
path: "Payload/Nested.app",
content: new Uint8Array(await readFile(nested)),
},
]);
const inventory = await inventoryApplicationPackage(path);
expect(inventory.subject?.format).toBe("ipa");
const occurrences = (
inventory.normalized_result as {
occurrences: Array<{
logical_path: string;
artifact_format: string;
}>;
}
).occurrences;
const nestedOccurrence = occurrences.find(
({ logical_path }) => logical_path === "Payload/Nested.app",
);
expect(nestedOccurrence?.artifact_format).toBe("zip");
});
it("claims the FA model only from config.json", async () => {
const path = await writeApplicationZip("rea-harmony-fa-", "Legacy.hap", [
{ path: "config.json", content: '{"app":{}}' },
{ path: "assets/js/default.js", content: "legacy();" },
{ path: "assets/entry/resources.index", content: "resource index" },
{
path: "assets/entry/resources/base/element/strings.json",
content: "{}",
},
{ path: "assets/feature/resources/rawfile/icon.png", content: "image" },
]);
const inventory = await inventoryApplicationPackage(path);
const result = projectHarmonyApplicationEvidence({
inventory_evidence: [inventory],
});
const projection = harmonyApplicationProjectionResultSchema.parse(
requireSuccessfulProjection(result).normalized_result,
);
expect(projection.packaging_model).toBe("fa");
expect(projection.runtime_families).toEqual(["javascript"]);
expect(projection.components.resources.map(({ path }) => path)).toEqual([
"assets/entry/resources.index",
"assets/entry/resources/base/element/strings.json",
"assets/feature/resources/rawfile/icon.png",
]);
});
it("rejects non-HarmonyOS inventory Evidence", async () => {
const inventory = await createNonApplicationZipInventory(
"rea-harmony-invalid-",
);
expect(
projectHarmonyApplicationEvidence({ inventory_evidence: [inventory] }),
).toMatchObject({
ok: false,
error: { _tag: "AnalysisInputError" },
});
});
it("keeps HTTP Archive .har files out of the HarmonyOS classification", async () => {
const root = await createTestTempDirectory("rea-harmony-http-har-");
const path = join(root, "capture.har");
await writeFile(
path,
JSON.stringify({ log: { version: "1.2", creator: {}, entries: [] } }),
);
const result = await runProviderAnalysis(path, "inventory_artifact", {});
expect(result).toMatchObject({
error: "Analysis failed",
code: "target_unavailable",
});
});
});
describe("HarmonyOS inventory coverage", () => {
it.each(ZIP_PACKAGE_FORMATS)(
"retains archive identity and ZIP coverage for %s",
async (format) => {
const suffix = format === "app-pack" ? "app" : format;
const path = await writeApplicationZip(
"rea-package-family-",
`Fixture.${suffix}`,
[{ path: "module.json", content: "{}" }],
);
const target = await parseBinaryTarget(path);
if (!target.ok) throw target.error;
expect(target.value).toMatchObject({ kind: "archive", format });
const evidence = await inventoryApplicationPackage(path);
const inventory = artifactInventoryResultSchema.parse(
evidence.normalized_result,
);
expect(
inventory.occurrences.find(({ logical_path }) => logical_path === "."),
).toMatchObject({
artifact_kind: "container",
artifact_format: format,
});
expect(inventory.limitations).toContain(ZIP_NON_ENTRY_TAIL_LIMITATION);
},
);
it("preserves unavailable encrypted component paths and qualifies absence", async () => {
const root = await createTestTempDirectory("rea-harmony-encrypted-");
const path = join(root, "Locked.hap");
const writer = new ZipWriter(new Uint8ArrayWriter());
await writer.add("module.json", new TextReader("{}"));
await writer.add("ets/modules.abc", new TextReader("opaque bytecode"), {
password: "fixture-only",
});
await writeFile(path, await writer.close());
const evidence = await inventoryApplicationPackage(path);
const projection = requireDeterministicProjection(
projectHarmonyApplicationEvidence,
evidence,
harmonyApplicationProjectionResultSchema,
);
expect(projection.components.bytecode).toEqual([]);
expect(projection.unavailable_components).toEqual([
expect.objectContaining({
path: "ets/modules.abc",
artifact_id: null,
sha256: null,
encrypted: true,
}),
]);
expect(projection.coverage).toEqual({
status: "partial",
inventory_complete: true,
});
expect(projection.limitations).toContainEqual(
expect.stringContaining("component and runtime absence is unknown"),
);
});
});
@@ -1,421 +0,0 @@
import { mkdir, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { createElectronActiveEvidence } from "../../../src/application/javascript/ElectronActiveEvidence.js";
import { reconcileJavaScriptRuntimeEvidence } from "../../../src/application/javascript/JavaScriptRuntimeReconciliationService.js";
import { createEvidence } from "../../../src/domain/evidence.js";
import {
parseRuntimeReconciliationInput,
reconcileJavaScriptRuntime,
} from "../../../src/domain/javascript/javascriptRuntimeReconciliation.js";
import { reconcileJavaScriptRuntimeInputSchema } from "../../../src/domain/javascript/javascriptRuntimeReconciliationSchemas.js";
import { javascriptRuntimeReconciliationResultSchema } from "../../../src/domain/javascript/javascriptRuntimeReconciliationSchemas.js";
import { electronActiveObservationInputSchema } from "../../../src/domain/javascript/electronActiveObservation.js";
import { createElectronActiveObservationFixtureResult } from "../../../src/domain/javascript/electronActiveObservation.fixture.js";
import {
SOURCE,
applicationFixture,
analyzeFixture,
electronRuntimeEvidence,
} from "../../fixtures/javascriptRuntimeReconciliation.js";
const reconcileInput = (input: unknown) =>
reconcileJavaScriptRuntime(
parseRuntimeReconciliationInput(
reconcileJavaScriptRuntimeInputSchema.parse(input),
),
);
it("preserves source-capture input paths for runtime Evidence", async () => {
const root = await applicationFixture();
const application = await analyzeFixture(root);
const runtime = electronRuntimeEvidence(root, SOURCE);
const invalidRuntime = createEvidence(undefined, runtime.provider, {
predicateType: runtime.predicate_type,
operation: runtime.operation,
parameters: { ...runtime.parameters, include_script_sources: false },
result: runtime.normalized_result,
confidence: runtime.confidence,
authority: runtime.authority,
});
const result = reconcileJavaScriptRuntimeEvidence({
static_layers: [{ role: "application", analysis: application }],
runtime_observations: [invalidRuntime],
});
expect(result).toMatchObject({
ok: false,
error: {
_tag: "AnalysisInputError",
issues: [
{
path: [
"runtime_observations",
0,
"parameters",
"include_script_sources",
],
reason: "invalid_value",
message:
"Runtime Evidence contains source without source-capture selection",
},
],
},
});
});
it("reconciles runtime scripts inside dot-prefixed child directories", async () => {
const root = await applicationFixture();
await mkdir(join(root, "..cache"));
await writeFile(join(root, "..cache", "app.js"), SOURCE);
const result = reconcileInput({
static_layers: [
{ role: "application", analysis: await analyzeFixture(root) },
],
runtime_observations: [
electronRuntimeEvidence(root, SOURCE, {
scriptFile: "..cache/app.js",
includeWorker: false,
}),
],
});
expect(result.reconciliations).toEqual(
expect.arrayContaining([
expect.objectContaining({
entity_kind: "script",
status: "matched",
basis: "content-and-location",
}),
]),
);
});
it("matches renderer, frame, script bytes, and worker without claiming execution", async () => {
const fixture = await applicationFixture();
const staticEvidence = await analyzeFixture(fixture);
const runtimeEvidence = electronRuntimeEvidence(fixture, SOURCE);
const result = reconcileInput({
static_layers: [{ role: "application", analysis: staticEvidence }],
runtime_observations: [runtimeEvidence],
});
expect(() =>
javascriptRuntimeReconciliationResultSchema.parse(result),
).not.toThrow();
expect(result.source_map_authority).toMatchObject({
used_for_primary_matching: false,
static_layer_count: 1,
runtime_script_declarations: 0,
});
expect(result.summary).toMatchObject({
runtime_targets: 1,
runtime_frames: 1,
runtime_scripts: 1,
runtime_workers: 1,
matched: 2,
ambiguous: 2,
unmatched: 0,
});
expect(result.reconciliations).toEqual(
expect.arrayContaining([
expect.objectContaining({
entity_kind: "script",
status: "matched",
basis: "content-and-location",
}),
expect.objectContaining({
entity_kind: "worker",
status: "matched",
basis: "artifact-path",
}),
expect.objectContaining({
entity_kind: "target",
status: "ambiguous",
reason: "ambiguous-static-candidates",
}),
]),
);
const matched = result.reconciliations.find(
({ status }) => status === "matched",
);
if (matched === undefined)
throw new TypeError("Expected one matched runtime reconciliation");
expect(
javascriptRuntimeReconciliationResultSchema.safeParse({
...result,
reconciliations: [{ ...matched, static_node_id: null }],
}).success,
).toBe(false);
expect(result.static_load_states).toEqual(
expect.arrayContaining([
expect.objectContaining({
kind: "javascript-asset",
status: "loaded",
}),
]),
);
expect(result.limitations.join(" ")).toMatch(
/not reported as executed|not code reachability/u,
);
expect(
result.graph.edges
.filter(({ relation }) => relation === "observed_as")
.every(
({ evidence }) =>
evidence.authority === "cross-layer-reconciliation" &&
evidence.state === "inferred",
),
).toBe(true);
const worker = result.reconciliations.find(
({ entity_kind: kind }) => kind === "worker",
);
const frame = result.reconciliations.find(
({ entity_kind: kind }) => kind === "frame",
);
expect(result.graph.edges).toContainEqual(
expect.objectContaining({
source_node_id: frame?.runtime_node_id,
target_node_id: worker?.runtime_node_id,
relation: "contains",
}),
);
});
it("keeps static load states unknown when one scoped capture omits scripts", async () => {
const fixture = await applicationFixture();
const staticEvidence = await analyzeFixture(fixture);
const result = reconcileInput({
static_layers: [{ role: "application", analysis: staticEvidence }],
runtime_observations: [
electronRuntimeEvidence(fixture, SOURCE, {
includeWorker: false,
targetId: "target-complete",
}),
electronRuntimeEvidence(fixture, SOURCE, {
includeWorker: false,
scriptsUnavailable: true,
targetId: "target-incomplete",
}),
],
});
expect(
result.runtime_captures.map(
({ scripts_complete_within_scope }) => scripts_complete_within_scope,
),
).toEqual(expect.arrayContaining([false, true]));
expect(result.summary.static_not_observed).toBe(0);
expect(result.static_load_states).toEqual(
expect.arrayContaining([
expect.objectContaining({
status: "unknown",
reason: "static-or-runtime-coverage-incomplete",
}),
]),
);
});
it("reports a captured digest disagreement instead of accepting a path match", async () => {
const fixture = await applicationFixture();
const staticEvidence = await analyzeFixture(fixture);
const runtimeEvidence = electronRuntimeEvidence(
fixture,
"export const observed = 'different';\n",
);
const result = reconcileInput({
static_layers: [{ role: "application", analysis: staticEvidence }],
runtime_observations: [runtimeEvidence],
});
const script = result.reconciliations.find(
({ entity_kind: kind }) => kind === "script",
);
expect(script).toMatchObject({
status: "unmatched",
reason: "captured-content-disagrees-with-static-location",
});
expect(script?.candidate_static_nodes).toHaveLength(1);
});
it("reconciles active Electron as a partial target-only runtime capture", async () => {
const fixture = await applicationFixture();
const staticEvidence = await analyzeFixture(fixture);
const applicationPath = join(fixture, "main.js");
const input = {
...electronActiveObservationInputSchema.parse({
executable_path: process.execPath,
application_path: applicationPath,
application_root: fixture,
actions: [],
}),
application_root: fixture,
};
const runtimeEvidence = createElectronActiveEvidence(
input,
createElectronActiveObservationFixtureResult(applicationPath),
{
id: "rea-playwright-electron-active",
name: "REA Playwright active Electron observation provider",
version: "1",
},
);
const result = reconcileInput({
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("commits complete Electron actions independently from selected arguments", async () => {
const fixture = await applicationFixture();
const applicationPath = join(fixture, "main.js");
const makeInput = (secret: string, selector: string) => ({
...electronActiveObservationInputSchema.parse({
executable_path: process.execPath,
application_path: applicationPath,
application_root: fixture,
args: ["--token", secret],
actions: [
{ step_id: "click", kind: "click", selector },
{ step_id: "settle", kind: "wait", duration_ms: 37 },
{
step_id: "open",
kind: "deep-link",
delivery: "second-instance",
url: "rea-fixture://open/item?token=selected",
},
],
}),
application_root: fixture,
});
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("first-secret", "#second-secret"),
createElectronActiveObservationFixtureResult(applicationPath),
provider,
);
expect(first.parameters.scenario_sha256).not.toBe(
second.parameters.scenario_sha256,
);
expect(JSON.stringify(first)).toContain("first-secret");
expect(first.parameters.actions).toEqual([
{
step_id: "click",
kind: "click",
selector: "#first-secret",
window_index: 0,
},
{ step_id: "settle", kind: "wait", duration_ms: 37 },
{
step_id: "open",
kind: "deep-link",
delivery: "second-instance",
url: "rea-fixture://open/item?token=selected",
},
]);
expect(first.parameters.args).toEqual(["--token", "first-secret"]);
});
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-");
const runtimeCache = await createTestTempDirectory("rea-runtime-cache-live-");
const cacheSource = SOURCE;
await mkdir(join(cache, "mapped"));
await Promise.all([
writeFile(join(cache, "mapped", "chunk.js"), cacheSource),
writeFile(join(cache, "outside.js"), "export const outside = true;\n"),
writeFile(join(runtimeCache, "chunk.js"), cacheSource),
writeFile(join(runtimeCache, "index.html"), "<script></script>"),
]);
const applicationEvidence = await analyzeFixture(application);
const cacheEvidence = await analyzeFixture(cache);
const runtimeEvidence = electronRuntimeEvidence(runtimeCache, cacheSource, {
scriptFile: "chunk.js",
includeWorker: false,
});
const result = reconcileInput({
static_layers: [
{ role: "application", analysis: applicationEvidence },
{
role: "cache",
analysis: cacheEvidence,
runtime_mappings: [
{
kind: "file-root",
root: runtimeCache,
artifact_prefix: "mapped",
},
],
},
],
runtime_observations: [runtimeEvidence],
});
const script = result.reconciliations.find(
({ entity_kind: kind }) => kind === "script",
);
const cacheLayer = result.static_layers.find(({ role }) => role === "cache");
expect(script).toMatchObject({
status: "matched",
basis: "content-and-location",
static_layer_id: cacheLayer?.layer_id,
});
const outside = result.graph.nodes.find(
(node) =>
node.kind === "javascript-asset" &&
node.observations.some(
({ properties }) => properties.path === "outside.js",
),
);
expect(
result.static_load_states.find(
({ static_node_id: nodeId }) => nodeId === outside?.node_id,
),
).toMatchObject({
status: "unknown",
reason: "layer-outside-runtime-scope",
});
const sharedFile = result.graph.nodes.find(
({ observations }) =>
observations.some(({ properties }) => properties.path === "app.js") &&
observations.some(
({ properties }) => properties.path === "mapped/chunk.js",
),
);
expect(
sharedFile?.observations.map(({ properties }) => properties.path),
).toEqual(expect.arrayContaining(["app.js", "mapped/chunk.js"]));
});