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:
@@ -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);
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user