test: overhaul deterministic suite architecture

This commit is contained in:
morluto
2026-07-29 22:00:38 +00:00
parent 7f2348619a
commit 513d9b1555
371 changed files with 30879 additions and 24389 deletions
@@ -0,0 +1,207 @@
import { describe, expect, it } from "vitest";
import {
bundleComparisonResultSchema,
compareBundles,
} from "../../../src/domain/bundleComparison.js";
import { createEvidence } from "../../../src/domain/evidence.js";
import { createEvidenceBundle } from "../../../src/domain/evidenceBundle.js";
import {
createResidualUnknown,
recordUnknownInputSchema,
updateResidualUnknown,
updateUnknownInputSchema,
} from "../../../src/domain/residualUnknown.js";
const PROVIDER = { id: "fixture", name: "Fixture", version: "1" } as const;
const evidence = (label: string) =>
createEvidence(undefined, PROVIDER, {
operation: "observe",
parameters: { label },
result: { label },
confidence: "derived",
authority: "analyst-inference",
});
describe("bundle comparison", () => {
it("returns unchanged only for equal canonical bundles", () => {
const first = evidence("first");
const second = evidence("second");
const left = createEvidenceBundle([first, second]);
const right = createEvidenceBundle([second, first]);
const result = compareBundles(left, right, [], 0, 100);
expect(bundleComparisonResultSchema.parse(result)).toMatchObject({
status: "unchanged",
summary: {
records_unchanged: 2,
records_added: 0,
records_removed: 0,
unresolved: 0,
},
changes: { total: 0, next_offset: null },
});
expect(result.left_bundle_sha256).toBe(result.right_bundle_sha256);
});
it("classifies explicit pairs and pages stable membership changes", () => {
const oldRecord = evidence("old");
const newRecord = evidence("new");
const removed = evidence("removed");
const added = evidence("added");
const left = createEvidenceBundle([oldRecord, removed]);
const right = createEvidenceBundle([newRecord, added]);
const pairs = [
{
left_evidence_id: oldRecord.evidence_id,
right_evidence_id: newRecord.evidence_id,
},
];
const first = compareBundles(left, right, pairs, 0, 1);
const repeated = compareBundles(left, right, pairs, 0, 1);
expect(first).toEqual(repeated);
expect(first).toMatchObject({
status: "changed",
summary: {
records_added: 1,
records_removed: 1,
records_changed: 1,
},
changes: { total: 3, next_offset: 1 },
});
expect(
compareBundles(left, right, pairs, 1, 500).changes.items,
).toHaveLength(2);
expect(first.limitations).toContain(
"One-sided membership proves only bundle inclusion or omission, not behavioral absence.",
);
});
it("rejects missing and non-bijective explicit pairs", () => {
const leftRecord = evidence("left");
const rightRecord = evidence("right");
const left = createEvidenceBundle([leftRecord]);
const right = createEvidenceBundle([rightRecord]);
expect(() =>
compareBundles(
left,
right,
[
{
left_evidence_id: evidence("missing").evidence_id,
right_evidence_id: rightRecord.evidence_id,
},
],
0,
100,
),
).toThrow(/missing left evidence/u);
expect(() =>
compareBundles(
left,
right,
[
{
left_evidence_id: leftRecord.evidence_id,
right_evidence_id: rightRecord.evidence_id,
},
{
left_evidence_id: leftRecord.evidence_id,
right_evidence_id: rightRecord.evidence_id,
},
],
0,
100,
),
).toThrow(/one-to-one/u);
expect(() =>
compareBundles(
{ ...left, records: [leftRecord, leftRecord] },
right,
[],
0,
100,
),
).toThrow(/duplicate record IDs/u);
});
});
describe("bundle comparison history", () => {
it("distinguishes advanced and missing unknown histories from equality", () => {
const mutationOne = evidence("mutation-one");
const initial = createResidualUnknown(
recordUnknownInputSchema.parse({
approved: true,
question: "Which branch remains unexplained?",
severity: "high",
domain: "comparison",
supporting_evidence_ids: [],
contradicting_evidence_ids: [],
required_authority: "shipped-artifact",
required_confidence: "observed",
required_environment: null,
recommended_probes: [],
relationships: [],
}),
mutationOne.evidence_id,
null,
);
const mutationTwo = evidence("mutation-two");
const advanced = updateResidualUnknown(
initial,
updateUnknownInputSchema.parse({
approved: true,
unknown_id: initial.unknown_id,
expected_revision: 1,
status: "investigating",
severity: initial.severity,
supporting_evidence_ids: [],
contradicting_evidence_ids: [],
required_authority: initial.required_authority,
required_confidence: initial.required_confidence,
required_environment: null,
recommended_probes: [],
relationships: [],
resolution: null,
}),
mutationTwo.evidence_id,
);
const initialBundle = createEvidenceBundle([mutationOne], [initial]);
const advancedBundle = createEvidenceBundle(
[mutationOne, mutationTwo],
[initial, advanced],
);
expect(
compareBundles(initialBundle, advancedBundle, [], 0, 100),
).toMatchObject({
status: "changed",
summary: { unknowns_advanced: 1, unresolved: 0 },
changes: {
items: [
expect.objectContaining({
entity: "evidence",
classification: "added",
}),
expect.objectContaining({
entity: "residual_unknown",
classification: "history_advanced",
}),
],
},
});
const absent = createEvidenceBundle([]);
const missing = compareBundles(initialBundle, absent, [], 0, 100);
expect(missing).toMatchObject({
status: "unknown",
summary: { unknowns_removed: 1, unresolved: 1 },
});
expect(missing.changes.items).toContainEqual(
expect.objectContaining({
classification: "removed",
conclusion_kind: "unresolved_branch",
limitations: [
"A missing unknown history does not establish resolution.",
],
}),
);
});
});
@@ -0,0 +1,340 @@
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { analyzeJavaScriptApplication } from "../../../src/application/JavaScriptApplicationService.js";
import { PermissionAuthority } from "../../../src/application/PermissionAuthority.js";
import { reconstructJavaScriptArtifact } from "../../../src/application/JavaScriptArtifactReconstruction.js";
import { parseEvidence } from "../../../src/domain/evidence.js";
import { parseJavaScriptApplicationGraph } from "../../../src/domain/javascriptApplicationGraph.js";
import { analyzeJavaScriptApplicationInputSchema } from "../../../src/domain/javascriptApplicationAnalysis.js";
import { createPermissionPolicy } from "../../../src/domain/permissionPolicy.js";
import { writeElectronBoundaryFixture } from "../../fixtures/electronBoundaryApplication.js";
describe("static Electron application analysis", () => {
it("requires explicit approval, an absolute path, and graph-safe combined bounds", () => {
expect(
analyzeJavaScriptApplicationInputSchema.safeParse({
input_path: "relative/app.asar",
approved: true,
}).success,
).toBe(false);
expect(
analyzeJavaScriptApplicationInputSchema.safeParse({
input_path: "/tmp/app.asar",
}).success,
).toBe(false);
expect(
analyzeJavaScriptApplicationInputSchema.safeParse({
input_path: "/tmp/app.asar",
approved: true,
limits: {
max_entries: 100_000,
max_findings: 200_000,
},
}).success,
).toBe(false);
expect(
analyzeJavaScriptApplicationInputSchema.parse({
input_path: "/tmp/app.asar",
approved: true,
}),
).toMatchObject({
format: "auto",
source_map_read_approved: false,
limits: { max_findings: 8_000 },
});
});
it("maps windows, preload, contextBridge, IPC, validations, utility, and native boundaries without execution", async () => {
const root = await fixtureDirectory();
Reflect.deleteProperty(globalThis, "__rea_electron_fixture_executed");
const first = await reconstructJavaScriptArtifact({ input_path: root });
const second = await reconstructJavaScriptArtifact({ input_path: root });
const graph = parseJavaScriptApplicationGraph(first.graph);
expect(
Reflect.get(globalThis, "__rea_electron_fixture_executed"),
).toBeUndefined();
expect(first.graph).toEqual(second.graph);
expectElectronSummary(first);
expectElectronRoles(graph);
expectElectronBoundaries(graph);
});
it("returns Evidence v2 only after exact investigation-input authorization", async () => {
const root = await fixtureDirectory();
const authority = permissionAuthority(root);
const result = await analyzeJavaScriptApplication(authority, {
input_path: root,
approved: true,
});
if (!result.ok) throw result.error;
const evidence = parseEvidence(result.value);
expect(evidence).toMatchObject({
operation: "analyze_javascript_application",
predicate_type: "rea.javascript-application-analysis/v2",
provider: { id: "rea-javascript-application" },
authority: "shipped-artifact",
confidence: "derived",
subject: { local_path: root, format: "directory" },
normalized_result: {
schema_version: 2,
input_path: root,
summary: { browser_windows: 3 },
},
});
const denied = await analyzeJavaScriptApplication(
permissionAuthority(root),
{
input_path: join(root, ".."),
approved: true,
},
);
expect(denied).toMatchObject({
ok: false,
error: { _tag: "PermissionRequiredError" },
});
});
it("returns a tagged cancellation without executing application code", async () => {
const root = await fixtureDirectory();
const controller = new AbortController();
controller.abort();
Reflect.deleteProperty(globalThis, "__rea_electron_fixture_executed");
const result = await analyzeJavaScriptApplication(
permissionAuthority(root),
{ input_path: root, approved: true },
{ signal: controller.signal },
);
expect(result).toMatchObject({
ok: false,
error: { _tag: "ArtifactOperationError", reason: "cancelled" },
});
expect(
Reflect.get(globalThis, "__rea_electron_fixture_executed"),
).toBeUndefined();
});
});
type Reconstruction = Awaited<ReturnType<typeof reconstructJavaScriptArtifact>>;
type ApplicationGraph = ReturnType<typeof parseJavaScriptApplicationGraph>;
const expectElectronSummary = (result: Reconstruction): void => {
expect(result.electron_summary).toMatchObject({
browser_windows: 3,
explicit_web_preferences: 8,
preload_entrypoints: 1,
context_bridge_apis: 2,
exposed_api_members: 5,
ipc: {
literal_channels: 5,
dynamic_channel_operations: 2,
paired_renderer_transmissions: 4,
ambiguous_renderer_transmissions: 1,
unpaired_literal_renderer_transmissions: 1,
},
sender_validation_observations: 2,
utility_processes: 1,
resolved_utility_entrypoints: 1,
native_addon_bindings: 4,
resolved_native_addon_bindings: 4,
});
};
const expectElectronRoles = (graph: ApplicationGraph): void => {
expect(graph.nodes.map(({ kind }) => kind)).toEqual(
expect.arrayContaining([
"browser-window",
"electron-preload",
"context-bridge-api",
"ipc-channel",
"ipc-handler",
"electron-utility",
"native-addon",
"native-export",
]),
);
const roles = graph.nodes.filter(({ kind }) =>
["electron-main", "electron-preload", "electron-renderer"].includes(kind),
);
expect(roles.length).toBeGreaterThanOrEqual(3);
for (const role of roles) {
for (const observation of role.observations)
expect(observation.properties).toMatchObject({
declared_path: expect.any(String),
resolution_context: expect.stringMatching(
/^(package-entrypoint|filesystem-expression|module-specifier|html-reference)$/u,
),
resolution_status: expect.stringMatching(
/^(resolved|not-found|unavailable|external|rejected)$/u,
),
limitations: expect.any(Array),
});
if (
role.observations.some(
({ properties }) => properties.resolution_status === "resolved",
)
)
expect(
graph.edges.some(
(edge) =>
edge.source_node_id === role.node_id && edge.relation === "maps_to",
),
).toBe(true);
}
const dirnamePreload = roles.find(
({ kind, observations }) =>
kind === "electron-preload" &&
observations.some(
({ properties }) =>
properties.declared_path === "preload.js" &&
properties.resolution_context === "filesystem-expression",
),
);
expect(dirnamePreload?.observations[0]?.properties).toMatchObject({
declared_path: "preload.js",
resolution_context: "filesystem-expression",
resolved_path: "preload.js",
resolution_status: "resolved",
limitations: [],
});
};
const expectElectronBoundaries = (graph: ApplicationGraph): void => {
expect(graph.nodes).toEqual(
expect.arrayContaining([
expect.objectContaining({
kind: "browser-window",
observations: expect.arrayContaining([
expect.objectContaining({
properties: expect.objectContaining({
preload_path: "preload.js",
absence_means_default: false,
web_preferences: expect.arrayContaining([
expect.objectContaining({
name: "nodeIntegration",
value: expect.objectContaining({
status: "literal",
value: true,
}),
}),
]),
}),
}),
]),
}),
expect.objectContaining({
kind: "browser-window",
observations: expect.arrayContaining([
expect.objectContaining({
properties: expect.objectContaining({
web_preferences: expect.arrayContaining([
expect.objectContaining({
name: "nodeIntegration",
value: expect.objectContaining({
status: "literal",
value: false,
}),
}),
expect.objectContaining({
name: "contextIsolation",
value: expect.objectContaining({
status: "literal",
value: true,
}),
}),
]),
}),
}),
]),
}),
expect.objectContaining({
kind: "context-bridge-api",
observations: expect.arrayContaining([
expect.objectContaining({
properties: expect.objectContaining({
api_key: "reaApi",
members: expect.arrayContaining([
"nested",
"nested.write",
"read",
]),
}),
}),
]),
}),
expect.objectContaining({
kind: "ipc-handler",
observations: expect.arrayContaining([
expect.objectContaining({
properties: expect.objectContaining({
fact_kind: "sender-validation-candidate",
enforcement: "unknown",
}),
}),
]),
}),
expect.objectContaining({
kind: "native-export",
observations: expect.arrayContaining([
expect.objectContaining({
properties: expect.objectContaining({
native_export_verification: "not-performed",
}),
}),
]),
}),
]),
);
const pairingEdges = graph.edges.filter(
({ properties }) =>
properties.pairing_basis === "unique-exact-literal-channel",
);
expect(pairingEdges).toHaveLength(4);
expect(
pairingEdges.some(
({ properties }) => properties.channel === "rea:ambiguous",
),
).toBe(false);
expect(graph.limitations.join(" ")).toMatch(/dynamic IPC|ambiguous/iu);
};
const fixtureDirectory = async (): Promise<string> => {
const root = await createTestTempDirectory("rea-electron-boundaries-");
await writeElectronBoundaryFixture(root);
return root;
};
const permissionAuthority = (root: string): PermissionAuthority =>
new PermissionAuthority(
createPermissionPolicy(
[scope(root)],
[
{
...scope(root),
grant_id: "test:investigation-input",
lifetime: "session",
operation_identity: null,
expires_at: null,
},
],
),
);
const scope = (root: string) => ({
capability: "investigation_input" as const,
roots: [root],
executables: [],
environment_names: [],
network: "none" as const,
mount: false,
});
@@ -0,0 +1,137 @@
import { describe, expect, it } from "vitest";
import {
computeJavaScriptApplicationGraphSha256,
createJavaScriptApplicationGraph,
javascriptApplicationGraphSchema,
parseJavaScriptApplicationGraph,
serializeJavaScriptApplicationGraph,
type ApplicationNode,
type JavaScriptApplicationGraph,
} from "../../../src/domain/javascriptApplicationGraph.js";
import {
JAVASCRIPT_APPLICATION_NODE_KINDS,
JAVASCRIPT_APPLICATION_RELATIONS,
} from "../../../src/domain/javascriptApplicationGraphSchemas.js";
import { buildSyntheticJavaScriptApplicationGraph } from "../../fixtures/javascriptApplicationGraph.js";
const nodeByLabel = (
graph: JavaScriptApplicationGraph,
label: string,
): ApplicationNode => {
const node = graph.nodes.find(({ observations }) =>
observations.some((observation) => observation.label === label),
);
if (node === undefined) throw new TypeError(`Missing fixture node: ${label}`);
return node;
};
describe("JavaScript Application Graph", () => {
it("defines the complete provider-neutral v1 node and relation vocabulary", () => {
expect(JAVASCRIPT_APPLICATION_NODE_KINDS).toEqual([
"package",
"installer",
"artifact",
"asar-entry",
"electron-main",
"electron-preload",
"electron-renderer",
"electron-utility",
"javascript-asset",
"javascript-chunk",
"javascript-module",
"source-map",
"source-module",
"browser-window",
"frame",
"target",
"context-bridge-api",
"ipc-channel",
"ipc-handler",
"worker",
"service-worker",
"endpoint",
"storage",
"native-addon",
"native-export",
"managed-assembly",
"managed-module",
"managed-type",
"managed-method",
"managed-field",
"managed-pinvoke-import",
"managed-native-implementation",
"runtime-script-instance",
"unknown",
]);
expect(JAVASCRIPT_APPLICATION_RELATIONS).toEqual([
"contains",
"loads",
"imports",
"maps_to",
"exposes",
"sends",
"invokes",
"handles",
"calls",
"persists_to",
"observed_as",
"changed_from",
]);
});
it("round-trips one canonical, versioned, byte-stable graph", () => {
const graph = buildSyntheticJavaScriptApplicationGraph();
const serialized = serializeJavaScriptApplicationGraph(graph);
const decoded: unknown = JSON.parse(serialized);
expect(parseJavaScriptApplicationGraph(decoded)).toEqual(graph);
expect(javascriptApplicationGraphSchema.parse(decoded)).toEqual(graph);
expect(serializeJavaScriptApplicationGraph(decoded)).toBe(serialized);
expect(computeJavaScriptApplicationGraphSha256(decoded)).toMatch(
/^[a-f0-9]{64}$/u,
);
const { graph_id: _graphId, ...semantic } = graph;
expect(
createJavaScriptApplicationGraph({
...semantic,
nodes: semantic.nodes.toReversed(),
edges: semantic.edges.toReversed(),
}),
).toEqual(graph);
});
it("represents the synthetic ASAR to preload to IPC to native chain", () => {
const graph = buildSyntheticJavaScriptApplicationGraph();
const labels = [
"resources/app.asar",
"desktop preload",
"desktopApi",
"project:open",
"project open handler",
"synthetic.node",
"openProject",
];
const chain = labels.map((label) => nodeByLabel(graph, label));
const expectedRelations = [
"contains",
"exposes",
"invokes",
"handles",
"loads",
"contains",
];
for (let index = 0; index < expectedRelations.length; index += 1)
expect(graph.edges).toContainEqual(
expect.objectContaining({
source_node_id: chain[index]?.node_id,
target_node_id: chain[index + 1]?.node_id,
relation: expectedRelations[index],
}),
);
expect(chain.at(-2)?.kind).toBe("native-addon");
expect(chain.at(-1)?.kind).toBe("native-export");
});
});
@@ -0,0 +1,191 @@
import { describe, expect, it } from "vitest";
import {
createJavaScriptApplicationGraph,
createJavaScriptApplicationNode,
type ApplicationGraphEvidence,
type ApplicationNode,
type JavaScriptApplicationGraph,
} from "../../../src/domain/javascriptApplicationGraph.js";
import {
APPLICATION_GRAPH_DIGESTS,
artifactEvidence,
buildSyntheticJavaScriptApplicationGraph,
} from "../../fixtures/javascriptApplicationGraph.js";
const completeCoverage = {
status: "complete" as const,
truncated: false,
omitted_count: 0,
limits: [],
};
const unknownEvidence = (
limitations: string[] = ["The extractor could not classify this fact."],
): ApplicationGraphEvidence => ({
authority: "unknown",
state: "unknown",
confidence: "unknown",
artifact: {
available: false,
reason: "unknown",
detail: "Artifact provenance is unknown.",
},
location: {
available: false,
reason: "unknown",
detail: "Source location is unknown.",
},
extractor: {
name: "test",
version: "1",
operation: "unknown",
executable_sha256: null,
},
coverage: {
status: "unknown",
truncated: false,
omitted_count: null,
limits: [],
},
limitations,
evidence_ids: [],
});
const nodeByLabel = (
graph: JavaScriptApplicationGraph,
label: string,
): ApplicationNode => {
const node = graph.nodes.find(({ observations }) =>
observations.some((observation) => observation.label === label),
);
if (node === undefined) throw new TypeError(`Missing fixture node: ${label}`);
return node;
};
const graphForNode = (node: ApplicationNode): JavaScriptApplicationGraph =>
createJavaScriptApplicationGraph({
schema: "JavaScriptApplicationGraph",
schema_version: 1,
root_node_ids: [node.node_id],
nodes: [node],
edges: [],
coverage: completeCoverage,
limitations: [],
});
describe("JavaScript Application Graph", () => {
it("keeps static observations, static inferences, runtime facts, and native facts distinct", () => {
const graph = buildSyntheticJavaScriptApplicationGraph();
const preload = nodeByLabel(graph, "desktop preload");
const runtime = nodeByLabel(graph, "preload runtime script");
const nativeExport = nodeByLabel(graph, "openProject");
const invoke = graph.edges.find(({ relation }) => relation === "invokes");
const observedAs = graph.edges.find(
({ relation }) => relation === "observed_as",
);
expect(preload.observations[0]?.evidence).toMatchObject({
authority: "ast-static-analysis",
state: "observed",
});
expect(invoke?.evidence).toMatchObject({
authority: "static-relationship-inference",
state: "inferred",
});
expect(runtime.observations[0]?.evidence).toMatchObject({
authority: "passive-cdp-runtime",
state: "observed",
});
expect(observedAs?.evidence.authority).toBe("passive-cdp-runtime");
expect(observedAs?.identifier_strategy).toEqual({
strategy: "semantic-content-sha256",
stability: "relationship-exact",
});
expect(runtime.observations[0]?.identifier_strategy).toEqual({
strategy: "semantic-content-sha256",
stability: "observation-exact",
});
expect(nativeExport.observations[0]?.evidence.authority).toBe(
"native-analysis-provider",
);
expect(preload.node_id).not.toBe(runtime.node_id);
});
it("retains explicit unknown observations without using them as identity proof", () => {
const node = createJavaScriptApplicationNode({
kind: "javascript-module",
identity: {
strategy: "content-digest",
stability: "global-exact",
sha256: APPLICATION_GRAPH_DIGESTS.asar,
},
observations: [
{
label: "observed module",
properties: {},
evidence: artifactEvidence(
APPLICATION_GRAPH_DIGESTS.asar,
"dist/module.js",
),
},
{
label: null,
properties: { question: "runtime correspondence" },
evidence: unknownEvidence(),
},
],
});
const graph = graphForNode(node);
expect(
graph.nodes[0]?.observations.find(
({ evidence }) => evidence.state === "unknown",
)?.evidence,
).toMatchObject({ authority: "unknown", confidence: "unknown" });
});
it("separates stable entity identity from changing observations", () => {
const identity = {
strategy: "canonical-path" as const,
stability: "artifact-version" as const,
artifact_sha256: APPLICATION_GRAPH_DIGESTS.asar,
path: "dist/chunk.js",
};
const first = createJavaScriptApplicationNode({
kind: "javascript-chunk",
identity,
observations: [
{
label: "first label",
properties: { modules: 10 },
evidence: artifactEvidence(
APPLICATION_GRAPH_DIGESTS.asar,
"dist/chunk.js",
"ast-static-analysis",
),
},
],
});
const second = createJavaScriptApplicationNode({
kind: "javascript-chunk",
identity,
observations: [
{
label: "renamed chunk",
properties: { modules: 11 },
evidence: artifactEvidence(
APPLICATION_GRAPH_DIGESTS.asar,
"dist/chunk.js",
"ast-static-analysis",
),
},
],
});
expect(first.node_id).toBe(second.node_id);
expect(first.observations[0]?.observation_id).not.toBe(
second.observations[0]?.observation_id,
);
});
});
@@ -0,0 +1,161 @@
import { describe, expect, it } from "vitest";
import {
createJavaScriptApplicationGraph,
createJavaScriptApplicationNode,
type ApplicationNode,
type JavaScriptApplicationGraph,
} from "../../../src/domain/javascriptApplicationGraph.js";
import {
APPLICATION_GRAPH_DIGESTS,
artifactEvidence,
buildSyntheticJavaScriptApplicationGraph,
inferredArtifactEvidence,
runtimeEvidence,
} from "../../fixtures/javascriptApplicationGraph.js";
const completeCoverage = {
status: "complete" as const,
truncated: false,
omitted_count: 0,
limits: [],
};
const nodeByLabel = (
graph: JavaScriptApplicationGraph,
label: string,
): ApplicationNode => {
const node = graph.nodes.find(({ observations }) =>
observations.some((observation) => observation.label === label),
);
if (node === undefined) throw new TypeError(`Missing fixture node: ${label}`);
return node;
};
const graphForNode = (node: ApplicationNode): JavaScriptApplicationGraph =>
createJavaScriptApplicationGraph({
schema: "JavaScriptApplicationGraph",
schema_version: 1,
root_node_ids: [node.node_id],
nodes: [node],
edges: [],
coverage: completeCoverage,
limitations: [],
});
describe("JavaScript Application Graph", () => {
it("normalizes structural identity and evidence set ordering", () => {
const evidence = inferredArtifactEvidence(
APPLICATION_GRAPH_DIGESTS.asar,
"dist/module.js",
);
evidence.limitations = ["z limitation", "a limitation", "a limitation"];
evidence.evidence_ids = [
`ev_${"b".repeat(64)}`,
`ev_${"a".repeat(64)}`,
`ev_${"a".repeat(64)}`,
];
evidence.coverage.limits = [
{ name: "modules", value: 100, unit: "items" },
{ name: "modules", value: 100, unit: "items" },
];
const node = createJavaScriptApplicationNode({
kind: "javascript-module",
identity: {
strategy: "structural-fingerprint",
stability: "cross-version-inference",
algorithm: "synthetic-v1",
fingerprint_sha256: "5".repeat(64),
basis: ["syntax-tree", "imports", "syntax-tree"],
},
observations: [{ label: "module", properties: {}, evidence }],
});
expect(node.identity).toMatchObject({ basis: ["imports", "syntax-tree"] });
expect(node.observations[0]?.evidence.limitations).toEqual([
"a limitation",
"z limitation",
]);
expect(node.observations[0]?.evidence.evidence_ids).toEqual([
`ev_${"a".repeat(64)}`,
`ev_${"b".repeat(64)}`,
]);
expect(node.observations[0]?.evidence.coverage.limits).toEqual([
{ name: "modules", value: 100, unit: "items" },
]);
expect(graphForNode(node).nodes).toEqual([node]);
});
it("scopes runtime identities to a capture and artifact paths to a version", () => {
const runtime = nodeByLabel(
buildSyntheticJavaScriptApplicationGraph(),
"preload runtime script",
);
const differentCapture = createJavaScriptApplicationNode({
kind: "runtime-script-instance",
identity: {
strategy: "runtime-instance",
stability: "capture-only",
capture_sha256: "6".repeat(64),
runtime_key: "script-preload",
},
observations: [
{
label: "other capture",
properties: {},
evidence: {
...runtimeEvidence("script-preload"),
location: {
available: true,
value: {
kind: "runtime",
capture_sha256: "6".repeat(64),
target_key: "target-main",
frame_key: "frame-main",
script_key: "script-preload",
},
},
},
},
],
});
expect(differentCapture.node_id).not.toBe(runtime.node_id);
const firstArtifact = createJavaScriptApplicationNode({
kind: "javascript-asset",
identity: {
strategy: "canonical-path",
stability: "artifact-version",
artifact_sha256: APPLICATION_GRAPH_DIGESTS.asar,
path: "dist/app.js",
},
observations: [
{
label: null,
properties: {},
evidence: artifactEvidence(
APPLICATION_GRAPH_DIGESTS.asar,
"dist/app.js",
),
},
],
});
const secondArtifact = createJavaScriptApplicationNode({
kind: "javascript-asset",
identity: {
strategy: "canonical-path",
stability: "artifact-version",
artifact_sha256: "7".repeat(64),
path: "dist/app.js",
},
observations: [
{
label: null,
properties: {},
evidence: artifactEvidence("7".repeat(64), "dist/app.js"),
},
],
});
expect(firstArtifact.node_id).not.toBe(secondArtifact.node_id);
});
});
@@ -0,0 +1,123 @@
import { describe, expect, it } from "vitest";
import {
createJavaScriptApplicationGraph,
createJavaScriptApplicationNode,
parseJavaScriptApplicationGraph,
type ApplicationNode,
type JavaScriptApplicationGraph,
} from "../../../src/domain/javascriptApplicationGraph.js";
import {
APPLICATION_GRAPH_DIGESTS,
artifactEvidence,
buildSyntheticJavaScriptApplicationGraph,
} from "../../fixtures/javascriptApplicationGraph.js";
const completeCoverage = {
status: "complete" as const,
truncated: false,
omitted_count: 0,
limits: [],
};
const firstOf = <Value>(values: readonly Value[], label: string): Value => {
const value = values[0];
if (value === undefined) throw new TypeError(`Missing fixture ${label}`);
return value;
};
const graphForNode = (node: ApplicationNode): JavaScriptApplicationGraph =>
createJavaScriptApplicationGraph({
schema: "JavaScriptApplicationGraph",
schema_version: 1,
root_node_ids: [node.node_id],
nodes: [node],
edges: [],
coverage: completeCoverage,
limitations: [],
});
describe("JavaScript Application Graph", () => {
it("admits source-map and observation-scoped identities only with supporting observations", () => {
const sourceModule = createJavaScriptApplicationNode({
kind: "source-module",
identity: {
strategy: "source-map-original",
stability: "source-map-exact",
source_map_sha256: APPLICATION_GRAPH_DIGESTS.asar,
original_source: "webpack:///src/editor.ts",
source_sha256: null,
},
observations: [
{
label: "src/editor.ts",
properties: { recovered_from: "source-map" },
evidence: artifactEvidence(
APPLICATION_GRAPH_DIGESTS.asar,
"dist/app.js.map",
"ast-static-analysis",
),
},
],
});
const observationScoped = createJavaScriptApplicationNode({
kind: "unknown",
identity: {
strategy: "observation-fingerprint",
stability: "observation-only",
observation_sha256: "8".repeat(64),
scope: "synthetic static inventory",
},
observations: [
{
label: "unclassified entity",
properties: {},
evidence: artifactEvidence(
APPLICATION_GRAPH_DIGESTS.asar,
"dist/app.js",
),
},
],
});
expect(graphForNode(sourceModule).nodes).toEqual([sourceModule]);
expect(graphForNode(observationScoped).nodes).toEqual([observationScoped]);
});
it("rejects unsupported versions, unknown fields, and stale commitments", () => {
const graph = buildSyntheticJavaScriptApplicationGraph();
expect(() =>
parseJavaScriptApplicationGraph({ ...graph, schema_version: 2 }),
).toThrow(/Unsupported JavaScript Application Graph schema version: 2/u);
expect(() =>
parseJavaScriptApplicationGraph({ ...graph, surprise: true }),
).toThrow();
const staleGraph = structuredClone(graph);
staleGraph.graph_id = `jag_${"f".repeat(64)}`;
expect(() => parseJavaScriptApplicationGraph(staleGraph)).toThrow(
/Graph identifier/u,
);
const staleNode = structuredClone(graph);
firstOf(staleNode.nodes, "node").node_id = `jag_node_${"f".repeat(64)}`;
expect(() => parseJavaScriptApplicationGraph(staleNode)).toThrow(
/Node identifier/u,
);
const staleObservation = structuredClone(graph);
firstOf(
firstOf(staleObservation.nodes, "node").observations,
"observation",
).observation_id = `jag_observation_${"f".repeat(64)}`;
expect(() => parseJavaScriptApplicationGraph(staleObservation)).toThrow(
/Observation identifier/u,
);
const staleEdge = structuredClone(graph);
firstOf(staleEdge.edges, "edge").edge_id = `jag_edge_${"f".repeat(64)}`;
expect(() => parseJavaScriptApplicationGraph(staleEdge)).toThrow(
/Edge identifier/u,
);
});
});
@@ -0,0 +1,159 @@
import { describe, expect, it } from "vitest";
import {
createJavaScriptApplicationEdge,
createJavaScriptApplicationGraph,
createJavaScriptApplicationNode,
type ApplicationNode,
type JavaScriptApplicationGraph,
} from "../../../src/domain/javascriptApplicationGraph.js";
import {
APPLICATION_GRAPH_DIGESTS,
artifactEvidence,
buildSyntheticJavaScriptApplicationGraph,
inferredArtifactEvidence,
} from "../../fixtures/javascriptApplicationGraph.js";
const completeCoverage = {
status: "complete" as const,
truncated: false,
omitted_count: 0,
limits: [],
};
const nodeByLabel = (
graph: JavaScriptApplicationGraph,
label: string,
): ApplicationNode => {
const node = graph.nodes.find(({ observations }) =>
observations.some((observation) => observation.label === label),
);
if (node === undefined) throw new TypeError(`Missing fixture node: ${label}`);
return node;
};
const firstOf = <Value>(values: readonly Value[], label: string): Value => {
const value = values[0];
if (value === undefined) throw new TypeError(`Missing fixture ${label}`);
return value;
};
describe("JavaScript Application Graph", () => {
it("rejects duplicate nodes, missing roots, dangling edges, and self edges", () => {
const graph = buildSyntheticJavaScriptApplicationGraph();
const { graph_id: _graphId, ...semantic } = graph;
const source = firstOf(semantic.nodes, "node");
expect(() =>
createJavaScriptApplicationGraph({
...semantic,
nodes: [...semantic.nodes, source],
}),
).toThrow(/Nodes must be sorted and unique/u);
expect(() =>
createJavaScriptApplicationGraph({
...semantic,
root_node_ids: [`jag_node_${"9".repeat(64)}`],
}),
).toThrow(/Root identifier/u);
const missingId = `jag_node_${"9".repeat(64)}`;
const dangling = createJavaScriptApplicationEdge({
source_node_id: source.node_id,
target_node_id: missingId,
relation: "loads",
properties: {},
evidence: inferredArtifactEvidence(
APPLICATION_GRAPH_DIGESTS.asar,
"dist/main.js",
),
});
expect(() =>
createJavaScriptApplicationGraph({
...semantic,
edges: [...semantic.edges, dangling],
}),
).toThrow(/endpoints must name graph nodes/u);
const selfEdge = createJavaScriptApplicationEdge({
source_node_id: source.node_id,
target_node_id: source.node_id,
relation: "imports",
properties: {},
evidence: inferredArtifactEvidence(
APPLICATION_GRAPH_DIGESTS.asar,
"dist/main.js",
),
});
expect(() =>
createJavaScriptApplicationGraph({
...semantic,
edges: [...semantic.edges, selfEdge],
}),
).toThrow(/self-referential/u);
});
it("allows changed_from only between entities of the same kind", () => {
const graph = buildSyntheticJavaScriptApplicationGraph();
const preload = nodeByLabel(graph, "desktop preload");
const runtime = nodeByLabel(graph, "preload runtime script");
const earlierPreload = createJavaScriptApplicationNode({
kind: "electron-preload",
identity: {
strategy: "canonical-path",
stability: "artifact-version",
artifact_sha256: "7".repeat(64),
path: "dist/preload.js",
},
observations: [
{
label: "earlier preload",
properties: {},
evidence: artifactEvidence("7".repeat(64), "dist/preload.js"),
},
],
});
const changedFrom = createJavaScriptApplicationEdge({
source_node_id: preload.node_id,
target_node_id: earlierPreload.node_id,
relation: "changed_from",
properties: {},
evidence: inferredArtifactEvidence(
APPLICATION_GRAPH_DIGESTS.asar,
"dist/preload.js",
),
});
expect(
createJavaScriptApplicationGraph({
schema: "JavaScriptApplicationGraph",
schema_version: 1,
root_node_ids: [preload.node_id],
nodes: [preload, earlierPreload],
edges: [changedFrom],
coverage: completeCoverage,
limitations: [],
}).edges,
).toEqual([changedFrom]);
const invalid = createJavaScriptApplicationEdge({
source_node_id: preload.node_id,
target_node_id: runtime.node_id,
relation: "changed_from",
properties: {},
evidence: inferredArtifactEvidence(
APPLICATION_GRAPH_DIGESTS.asar,
"dist/preload.js",
),
});
expect(() =>
createJavaScriptApplicationGraph({
schema: "JavaScriptApplicationGraph",
schema_version: 1,
root_node_ids: [preload.node_id],
nodes: [preload, runtime],
edges: [invalid],
coverage: completeCoverage,
limitations: [],
}),
).toThrow(/changed_from endpoints must have the same node kind/u);
});
});
@@ -0,0 +1,211 @@
import { describe, expect, it } from "vitest";
import {
createJavaScriptApplicationGraph,
createJavaScriptApplicationNode,
type ApplicationGraphEvidence,
type ApplicationNode,
type JavaScriptApplicationGraph,
} from "../../../src/domain/javascriptApplicationGraph.js";
import {
APPLICATION_GRAPH_DIGESTS,
artifactEvidence,
inferredArtifactEvidence,
runtimeEvidence,
} from "../../fixtures/javascriptApplicationGraph.js";
const completeCoverage = {
status: "complete" as const,
truncated: false,
omitted_count: 0,
limits: [],
};
const unknownEvidence = (
limitations: string[] = ["The extractor could not classify this fact."],
): ApplicationGraphEvidence => ({
authority: "unknown",
state: "unknown",
confidence: "unknown",
artifact: {
available: false,
reason: "unknown",
detail: "Artifact provenance is unknown.",
},
location: {
available: false,
reason: "unknown",
detail: "Source location is unknown.",
},
extractor: {
name: "test",
version: "1",
operation: "unknown",
executable_sha256: null,
},
coverage: {
status: "unknown",
truncated: false,
omitted_count: null,
limits: [],
},
limitations,
evidence_ids: [],
});
const graphForNode = (node: ApplicationNode): JavaScriptApplicationGraph =>
createJavaScriptApplicationGraph({
schema: "JavaScriptApplicationGraph",
schema_version: 1,
root_node_ids: [node.node_id],
nodes: [node],
edges: [],
coverage: completeCoverage,
limitations: [],
});
const contentNode = (
evidence: ApplicationGraphEvidence,
properties: Record<string, unknown> = {},
): ApplicationNode =>
createJavaScriptApplicationNode({
kind: "javascript-module",
identity: {
strategy: "content-digest",
stability: "global-exact",
sha256: APPLICATION_GRAPH_DIGESTS.asar,
},
observations: [{ label: "module", properties, evidence }],
});
describe("JavaScript Application Graph", () => {
it("requires every identity strategy to have compatible supporting evidence", () => {
const mismatchedPath = createJavaScriptApplicationNode({
kind: "javascript-asset",
identity: {
strategy: "canonical-path",
stability: "artifact-version",
artifact_sha256: APPLICATION_GRAPH_DIGESTS.asar,
path: "dist/expected.js",
},
observations: [
{
label: null,
properties: {},
evidence: artifactEvidence(
APPLICATION_GRAPH_DIGESTS.asar,
"dist/other.js",
),
},
],
});
expect(() => graphForNode(mismatchedPath)).toThrow(
/identity is not supported/u,
);
const runtimeWithStaticEvidence = createJavaScriptApplicationNode({
kind: "runtime-script-instance",
identity: {
strategy: "runtime-instance",
stability: "capture-only",
capture_sha256: APPLICATION_GRAPH_DIGESTS.capture,
runtime_key: "script-preload",
},
observations: [
{
label: null,
properties: {},
evidence: artifactEvidence(
APPLICATION_GRAPH_DIGESTS.asar,
"dist/preload.js",
"ast-static-analysis",
),
},
],
});
expect(() => graphForNode(runtimeWithStaticEvidence)).toThrow(
/identity is not supported/u,
);
const mismatchedDigest = contentNode(
artifactEvidence("7".repeat(64), "dist/module.js"),
);
expect(() => graphForNode(mismatchedDigest)).toThrow(
/identity is not supported/u,
);
});
it("prevents static authorities from claiming runtime locations", () => {
const evidence = artifactEvidence(
APPLICATION_GRAPH_DIGESTS.asar,
"dist/module.js",
"ast-static-analysis",
);
evidence.location = runtimeEvidence("script-module").location;
expect(() => graphForNode(contentNode(evidence))).toThrow(
/cannot claim a runtime location/u,
);
});
it("enforces epistemic truthfulness and content-addressed artifacts", () => {
const inferredAsObserved = inferredArtifactEvidence(
APPLICATION_GRAPH_DIGESTS.asar,
"dist/module.js",
);
inferredAsObserved.state = "observed";
inferredAsObserved.confidence = "exact";
expect(() => contentNode(inferredAsObserved)).toThrow(
/must remain inferred/u,
);
const inferenceWithoutLimit = inferredArtifactEvidence(
APPLICATION_GRAPH_DIGESTS.asar,
"dist/module.js",
);
inferenceWithoutLimit.limitations = [];
expect(() => contentNode(inferenceWithoutLimit)).toThrow(
/Inferred facts require an explicit limitation/u,
);
const unknownWithoutLimit = unknownEvidence([]);
expect(() => contentNode(unknownWithoutLimit)).toThrow(
/require unknown confidence and an explicit limitation/u,
);
const missingArtifact = artifactEvidence(
APPLICATION_GRAPH_DIGESTS.asar,
"dist/module.js",
);
missingArtifact.artifact = {
available: false,
reason: "not-observed",
detail: "Bytes were not observed.",
};
expect(() => contentNode(missingArtifact)).toThrow(
/require a content digest/u,
);
const mismatchedArtifact = artifactEvidence(
APPLICATION_GRAPH_DIGESTS.asar,
"dist/module.js",
);
if (mismatchedArtifact.artifact.available)
mismatchedArtifact.artifact.artifact_id = `art_${"8".repeat(64)}`;
expect(() => contentNode(mismatchedArtifact)).toThrow(
/same SHA-256 digest/u,
);
const unlocatedObservation = artifactEvidence(
APPLICATION_GRAPH_DIGESTS.asar,
"dist/module.js",
);
unlocatedObservation.location = {
available: false,
reason: "not-observed",
detail: "The exact location was not recorded.",
};
expect(() => contentNode(unlocatedObservation)).toThrow(
/Observed facts require an actionable location/u,
);
});
});
@@ -0,0 +1,88 @@
import { describe, expect, it } from "vitest";
import {
createJavaScriptApplicationGraph,
createJavaScriptApplicationNode,
type ApplicationGraphEvidence,
type ApplicationNode,
} from "../../../src/domain/javascriptApplicationGraph.js";
import {
APPLICATION_GRAPH_DIGESTS,
artifactEvidence,
} from "../../fixtures/javascriptApplicationGraph.js";
const contentNode = (
evidence: ApplicationGraphEvidence,
properties: Record<string, unknown> = {},
): ApplicationNode =>
createJavaScriptApplicationNode({
kind: "javascript-module",
identity: {
strategy: "content-digest",
stability: "global-exact",
sha256: APPLICATION_GRAPH_DIGESTS.asar,
},
observations: [{ label: "module", properties, evidence }],
});
describe("JavaScript Application Graph", () => {
it("rejects false truncation claims and unbounded properties", () => {
const truncated = artifactEvidence(
APPLICATION_GRAPH_DIGESTS.asar,
"dist/module.js",
);
truncated.coverage = {
status: "partial",
truncated: true,
omitted_count: 0,
limits: [],
};
expect(() => contentNode(truncated)).toThrow(
/must be partial, name a limit, and not claim zero omissions/u,
);
const nonComplete = artifactEvidence(
APPLICATION_GRAPH_DIGESTS.asar,
"dist/module.js",
);
nonComplete.coverage = {
status: "partial",
truncated: false,
omitted_count: null,
limits: [],
};
expect(() => contentNode(nonComplete)).toThrow(
/Non-complete coverage requires an explicit limitation/u,
);
const validNode = contentNode(
artifactEvidence(APPLICATION_GRAPH_DIGESTS.asar, "dist/module.js"),
);
expect(() =>
createJavaScriptApplicationGraph({
schema: "JavaScriptApplicationGraph",
schema_version: 1,
root_node_ids: [validNode.node_id],
nodes: [validNode],
edges: [],
coverage: {
status: "partial",
truncated: false,
omitted_count: null,
limits: [],
},
limitations: [],
}),
).toThrow(/Non-complete graph coverage requires an explicit limitation/u);
const properties = Object.fromEntries(
Array.from({ length: 65 }, (_, index) => [`key-${String(index)}`, index]),
);
expect(() =>
contentNode(
artifactEvidence(APPLICATION_GRAPH_DIGESTS.asar, "dist/module.js"),
properties,
),
).toThrow(/exceed 64 keys/u);
});
});
@@ -0,0 +1,322 @@
import { describe, expect, it } from "vitest";
import {
resolveArtifactPathByContext,
type ResolveArtifactPathInput,
} from "../../../src/application/JavaScriptArtifactPathResolution.js";
import type { JavaScriptArtifactFile } from "../../../src/application/JavaScriptArtifactFiles.js";
import { analyzeJavaScriptStaticSource } from "../../../src/domain/javascriptStaticAnalysis.js";
describe("contextual JavaScript artifact path resolution", () => {
it.each([
["main.js", "app/main.js"],
["./main.js", "app/main.js"],
["src/main", "app/src/main.cjs"],
["entry", "app/entry/start.mjs"],
["fallback", "app/fallback/index.ts"],
])("resolves package entrypoint %s", (declaredPath, expected) => {
const files = fileMap([
file("app/package.json", "root"),
file("app/main.js", "root"),
file("app/src/main.cjs", "root"),
file("app/entry/package.json", "root", '{"main":"start"}'),
file("app/entry/start.mjs", "root"),
file("app/fallback/index.ts", "root"),
]);
expect(
resolve({
declaredPath,
sourcePath: "app/package.json",
context: "package-entrypoint",
files,
}),
).toMatchObject({
resolution_context: "package-entrypoint",
resolution_status: "resolved",
resolved_path: expected,
limitations: [],
});
});
it("resolves dirname-derived bare paths but keeps bare module specifiers external", () => {
const files = fileMap([
file("app/main.js", "root"),
file("app/preload.js", "root"),
]);
const base = {
declaredPath: "preload.js",
sourcePath: "app/main.js",
files,
} as const;
expect(
resolve({ ...base, context: "filesystem-expression" }),
).toMatchObject({
resolution_status: "resolved",
resolved_path: "app/preload.js",
});
expect(resolve({ ...base, context: "module-specifier" })).toMatchObject({
resolution_status: "external",
resolved_path: null,
});
});
it("applies document and base-href semantics to HTML references", () => {
const files = fileMap([
file("renderer/index.html", "root"),
file("assets/app.js", "root"),
file("renderer/local.js", "root"),
]);
expect(
resolve({
declaredPath: "app.js?v=1",
sourcePath: "renderer/index.html",
context: "html-reference",
htmlBaseHref: "/assets/",
files,
}),
).toMatchObject({
resolution_status: "resolved",
resolved_path: "assets/app.js",
});
expect(
resolve({
declaredPath: "./local.js",
sourcePath: "renderer/index.html",
context: "html-reference",
files,
}),
).toMatchObject({
resolution_status: "resolved",
resolved_path: "renderer/local.js",
});
expect(
resolve({
declaredPath: "file:///assets/app.js#entry",
sourcePath: "main.js",
context: "module-specifier",
files,
}),
).toMatchObject({
resolution_status: "resolved",
resolved_path: "assets/app.js",
});
});
it.each(["node:fs", "electron", "../../escape.js", "%2e%2e/escape.js"])(
"fails closed for unsafe or external module declaration %s",
(declaredPath) => {
const result = resolve({
declaredPath,
sourcePath: "app/main.js",
context: "module-specifier",
files: fileMap([file("app/main.js", "root")]),
});
expect(result.resolved_path).toBeNull();
expect(["external", "rejected"]).toContain(result.resolution_status);
expect(result.limitations.length).toBeGreaterThan(0);
},
);
it("does not cross nested ASAR container identities", () => {
const files = fileMap([
file("app.asar/main.js", "asar-a"),
file("app.asar/preload.js", "asar-b"),
]);
expect(
resolve({
declaredPath: "preload.js",
sourcePath: "app.asar/main.js",
context: "filesystem-expression",
files,
}),
).toMatchObject({ resolution_status: "not-found", resolved_path: null });
});
});
describe("contextual JavaScript package path resolution", () => {
it("keeps an inventoried but unreadable directory package unavailable", () => {
const files = fileMap([
file("app/package.json", "root"),
file("app/entry/package.json", "root", null),
]);
expect(
resolve({
declaredPath: "entry",
sourcePath: "app/package.json",
context: "package-entrypoint",
files,
}),
).toMatchObject({
resolution_status: "unavailable",
resolved_path: null,
limitations: [expect.stringContaining("text is unavailable")],
});
});
it("resolves nearest inventoried bare packages with import/require conditions", () => {
const files = fileMap([
file("app/src/consumer.js", "root"),
file(
"app/node_modules/fixture/package.json",
"root",
JSON.stringify({
exports: {
".": {
import: "./esm.mjs",
require: "./cjs.cjs",
default: "./fallback.js",
},
},
}),
),
file("app/node_modules/fixture/esm.mjs", "root"),
file("app/node_modules/fixture/cjs.cjs", "root"),
file("app/node_modules/fixture/fallback.js", "root"),
file("app/node_modules/fixture/hidden.js", "root"),
file("app/node_modules/fs/index.js", "root"),
]);
expect(
resolve({
declaredPath: "fixture",
sourcePath: "app/src/consumer.js",
context: "module-specifier",
moduleKind: "import",
files,
}),
).toMatchObject({
resolution_status: "resolved",
resolved_path: "app/node_modules/fixture/esm.mjs",
});
expect(
resolve({
declaredPath: "fixture",
sourcePath: "app/src/consumer.js",
context: "module-specifier",
moduleKind: "require",
files,
}),
).toMatchObject({
resolution_status: "resolved",
resolved_path: "app/node_modules/fixture/cjs.cjs",
});
expect(
resolve({
declaredPath: "fs",
sourcePath: "app/src/consumer.js",
context: "module-specifier",
moduleKind: "require",
files,
}),
).toMatchObject({ resolution_status: "external", resolved_path: null });
expect(
resolve({
declaredPath: "fixture/hidden.js",
sourcePath: "app/src/consumer.js",
context: "module-specifier",
moduleKind: "import",
files,
}),
).toMatchObject({
resolution_status: "external",
resolved_path: null,
limitations: [expect.stringContaining("subpaths remain unresolved")],
});
});
});
describe("contextual JavaScript module identity", () => {
it("retains CommonJS and ESM file-base identity during inert extraction", () => {
const analysis = analyzeJavaScriptStaticSource(
`
new BrowserWindow({ webPreferences: {
preload: path.resolve(__dirname, "preload.cjs")
}});
new BrowserWindow({ webPreferences: {
preload: fileURLToPath(new URL("./preload.mjs", import.meta.url))
}});
new BrowserWindow({ webPreferences: {
preload: path.join(path.dirname(__filename), "legacy-preload.js")
}});
new BrowserWindow({ webPreferences: {
preload: new URL("./remote-base.js", location.href)
}});
window.loadURL("file:///renderer/index.html");
`,
{
maxAstNodes: 10_000,
maxFindings: 100,
maxModules: 100,
deadline: Number.POSITIVE_INFINITY,
now: () => 0,
},
);
expect(analysis.role_paths).toEqual(
expect.arrayContaining([
expect.objectContaining({
path: "preload.cjs",
resolution_context: "filesystem-expression",
}),
expect.objectContaining({
path: "./preload.mjs",
resolution_context: "filesystem-expression",
}),
expect.objectContaining({
path: "legacy-preload.js",
resolution_context: "filesystem-expression",
}),
expect.objectContaining({
path: "file:///renderer/index.html",
resolution_context: "module-specifier",
}),
]),
);
expect(analysis.electron.browser_windows).toEqual(
expect.arrayContaining([
expect.objectContaining({
preload_path: "preload.cjs",
preload_resolution_context: "filesystem-expression",
}),
expect.objectContaining({
preload_path: "./preload.mjs",
preload_resolution_context: "filesystem-expression",
}),
]),
);
expect(analysis.role_paths).not.toEqual(
expect.arrayContaining([
expect.objectContaining({ path: "./remote-base.js" }),
]),
);
});
});
const resolve = (input: ResolveArtifactPathInput) =>
resolveArtifactPathByContext(input);
const fileMap = (files: readonly JavaScriptArtifactFile[]) =>
new Map(files.map((value) => [value.path, value]));
const file = (
path: string,
container: string,
text: string | null = "",
): JavaScriptArtifactFile => ({
path,
container_sha256: container.padEnd(64, "0").slice(0, 64),
sha256: path.padEnd(64, "0").slice(0, 64),
bytes: text?.length ?? 0,
inventory_artifact_id: `artifact-${path}`,
kind: path.endsWith("package.json") ? "package-json" : "javascript",
unpacked: false,
text:
text === null
? { included: false, reason: "file-limit" }
: { included: true, value: text },
});
@@ -0,0 +1,331 @@
import { mkdir, rm } from "node:fs/promises";
import { join } from "node:path";
import { createPackageWithOptions } from "@electron/asar";
import { expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { reconstructJavaScriptArtifact } from "../../../src/application/JavaScriptArtifactReconstruction.js";
import { scanArtifactInventory } from "../../../src/application/ArtifactInventory.js";
import { parseJavaScriptApplicationGraph } from "../../../src/domain/javascriptApplicationGraph.js";
import { javaScriptApplicationAnalysisResultV2Schema } from "../../../src/domain/javascriptApplicationAnalysis.js";
import { createJavaScriptSemanticGraph } from "../../../src/domain/javascriptSemanticGraph.js";
import { parseJavaScriptSemanticGraph } from "../../../src/domain/javascriptSemanticGraphSerialization.js";
import { writeJavaScriptArtifactFixture } from "../../fixtures/javascriptArtifactApplication.js";
it("reconstructs package, Electron roles, Webpack/Rspack modules, and cross-layer facts without execution", async () => {
const root = await fixtureDirectory();
Reflect.deleteProperty(globalThis, "__rea_bundle_executed");
const result = await reconstructJavaScriptArtifact({
input_path: root,
source_map_read_approved: true,
});
const graph = parseJavaScriptApplicationGraph(result.graph);
const semanticGraph = parseJavaScriptSemanticGraph(result.semantic_graph);
expect(Reflect.get(globalThis, "__rea_bundle_executed")).toBeUndefined();
expect(result.input_path).toBe(root);
expect(result.statistics).toMatchObject({
modules: 4,
parse_failures: 0,
omitted_text_files: 0,
policy_filtered_text_files: 0,
});
expect(graph.nodes.map(({ kind }) => kind)).toEqual(
expect.arrayContaining([
"package",
"artifact",
"electron-main",
"electron-preload",
"electron-renderer",
"javascript-asset",
"javascript-chunk",
"javascript-module",
"worker",
"service-worker",
"endpoint",
"storage",
"source-map",
"source-module",
"native-addon",
]),
);
expect(graph.nodes.filter(({ kind }) => kind === "javascript-chunk")).toEqual(
expect.arrayContaining([
expect.objectContaining({
observations: expect.arrayContaining([
expect.objectContaining({
properties: expect.objectContaining({ bundler: "webpack" }),
}),
]),
}),
expect.objectContaining({
observations: expect.arrayContaining([
expect.objectContaining({
properties: expect.objectContaining({ bundler: "rspack" }),
}),
]),
}),
]),
);
expect(
graph.nodes.filter(({ kind }) => kind === "javascript-module"),
).toEqual(
expect.arrayContaining([
expect.objectContaining({
observations: expect.arrayContaining([
expect.objectContaining({
properties: expect.objectContaining({
module_key: "1",
structural_fingerprint_algorithm: "babel-ast-v1",
}),
}),
]),
}),
]),
);
expect(graph.edges.map(({ relation }) => relation)).toEqual(
expect.arrayContaining([
"contains",
"loads",
"imports",
"maps_to",
"exposes",
"calls",
"persists_to",
]),
);
assertSemanticLinks(result, graph, semanticGraph);
});
it("produces deterministic ASAR graphs with unpacked native linkage and complete paths/digests", async () => {
const root = await createTestTempDirectory("rea-javascript-asar-");
const source = join(root, "source");
await mkdir(source);
await writeJavaScriptArtifactFixture(source);
const archive = join(root, "app.asar");
await createPackageWithOptions(source, archive, { unpack: "**/*.node" });
const first = await reconstructJavaScriptArtifact({
input_path: archive,
format: "asar",
source_map_read_approved: true,
});
const second = await reconstructJavaScriptArtifact({
input_path: archive,
format: "asar",
source_map_read_approved: true,
});
expect(first.graph).toEqual(second.graph);
expect(first.inventory_graph_sha256).toBe(second.inventory_graph_sha256);
expect(first.graph.graph_id).toBe(second.graph.graph_id);
expect(first.graph.nodes).toEqual(
expect.arrayContaining([
expect.objectContaining({
kind: "asar-entry",
observations: expect.arrayContaining([
expect.objectContaining({
properties: expect.objectContaining({
entry_sha256: expect.stringMatching(/^[a-f0-9]{64}$/u),
inventory_artifact_id:
expect.stringMatching(/^art_[a-f0-9]{64}$/u),
}),
}),
]),
}),
expect.objectContaining({
kind: "native-addon",
observations: expect.arrayContaining([
expect.objectContaining({
properties: expect.objectContaining({
path: "native/addon.node",
unpacked: true,
}),
}),
]),
}),
]),
);
expect(first.graph.edges).toContainEqual(
expect.objectContaining({
relation: "loads",
properties: expect.objectContaining({
resolved_path: "native/addon.node",
}),
}),
);
});
it("keeps ASAR analysis usable when unpacked native companion bytes are absent", async () => {
const root = await createTestTempDirectory("rea-javascript-asar-missing-");
const source = join(root, "source");
await mkdir(source);
await writeJavaScriptArtifactFixture(source);
const archive = join(root, "app.asar");
await createPackageWithOptions(source, archive, { unpack: "**/*.node" });
await rm(join(`${archive}.unpacked`, "native", "addon.node"));
const snapshot = await scanArtifactInventory(archive, {
maxEntries: 8_000,
maxTotalBytes: 512 * 1024 * 1024,
maxEntryBytes: 128 * 1024 * 1024,
maxCompressionRatio: 1_000,
maxDepth: 64,
maxPathBytes: 4_096,
});
const missingNative = snapshot.occurrences.find(
({ logical_path }) => logical_path === "native/addon.node",
);
expect(missingNative).toMatchObject({
artifact_id: null,
hash_status: "unavailable",
limitations: expect.arrayContaining([
"ASAR unpacked companion bytes were unavailable; no content hash or child artifact was produced.",
]),
});
const result = await reconstructJavaScriptArtifact({
input_path: archive,
format: "asar",
source_map_read_approved: true,
});
expect(result.statistics.parsed_javascript_files).toBeGreaterThan(0);
expect(result.graph.nodes).toEqual(
expect.arrayContaining([
expect.objectContaining({ kind: "javascript-asset" }),
]),
);
});
it("recurses into filesystem-backed ASAR containers without losing container-relative paths", async () => {
const root = await createTestTempDirectory("rea-javascript-nested-asar-");
const source = await fixtureDirectory();
const outer = join(root, "outer");
const resources = join(outer, "resources");
await mkdir(resources, { recursive: true });
await createPackageWithOptions(source, join(resources, "app.asar"), {
unpack: "**/*.node",
});
const result = await reconstructJavaScriptArtifact({
input_path: outer,
source_map_read_approved: true,
});
expect(result.statistics.nested_asar_containers).toBe(1);
expect(result.statistics.modules).toBe(4);
expect(result.graph.nodes).toEqual(
expect.arrayContaining([
expect.objectContaining({
kind: "artifact",
observations: expect.arrayContaining([
expect.objectContaining({
label: "resources/app.asar",
properties: expect.objectContaining({ format: "asar" }),
}),
]),
}),
expect.objectContaining({
kind: "javascript-asset",
observations: expect.arrayContaining([
expect.objectContaining({
properties: expect.objectContaining({
path: "resources/app.asar/main.js",
}),
}),
]),
}),
]),
);
});
const assertSemanticLinks = (
result: Awaited<ReturnType<typeof reconstructJavaScriptArtifact>>,
graph: ReturnType<typeof parseJavaScriptApplicationGraph>,
semanticGraph: ReturnType<typeof parseJavaScriptSemanticGraph>,
) => {
expect(semanticGraph.application_graph_id).toBe(graph.graph_id);
const { graph_id: _semanticGraphId, ...semanticGraphInput } = semanticGraph;
const mismatchedSemanticGraph = createJavaScriptSemanticGraph({
...semanticGraphInput,
application_graph_id: `jag_${"f".repeat(64)}`,
});
const { electron_summary: summary, ...analysisResult } = result;
expect(() =>
javaScriptApplicationAnalysisResultV2Schema.parse({
...analysisResult,
schema_version: 2,
summary,
semantic_graph: mismatchedSemanticGraph,
}),
).toThrow(/must commit the containing application graph/u);
expect(
semanticGraph.nodes.some(
({ application_node_ids: identifiers }) => identifiers.length > 0,
),
).toBe(true);
expect(semanticGraph.relations.length).toBeGreaterThan(0);
const roles = ["electron-main", "electron-preload"].map((kind) =>
graph.nodes.find((node) => node.kind === kind),
);
expect(roles[0]?.observations[0]?.properties).toMatchObject({
declared_path: "main.js",
resolution_context: "package-entrypoint",
resolved_path: "main.js",
resolution_status: "resolved",
limitations: [],
});
expect(roles[1]?.observations[0]?.properties).toMatchObject({
declared_path: "preload.js",
resolution_context: "filesystem-expression",
resolved_path: "preload.js",
resolution_status: "resolved",
limitations: [],
});
const mainAsset = graph.nodes.find(
(node) =>
node.kind === "javascript-asset" &&
node.observations.some(
({ evidence }) =>
evidence.location.available &&
evidence.location.value.kind === "artifact-path" &&
evidence.location.value.path === "main.js",
),
);
if (mainAsset === undefined)
throw new Error("Expected main JavaScript asset");
const mainSemanticNodes = semanticGraph.nodes.filter(
({ identity }) => identity.module_path === "main.js",
);
const linkedMainSemanticNodes = mainSemanticNodes.filter(
({ application_node_ids: identifiers }) =>
identifiers.includes(mainAsset.node_id),
);
expect(linkedMainSemanticNodes.length).toBeGreaterThan(0);
expect(linkedMainSemanticNodes.length).toBeLessThan(mainSemanticNodes.length);
for (const role of roles) {
expect(role).toBeDefined();
expect(
graph.edges.some(
(edge) =>
edge.source_node_id === role?.node_id && edge.relation === "maps_to",
),
).toBe(true);
}
const endpointJson = JSON.stringify(
graph.nodes.filter(({ kind }) => kind === "endpoint"),
);
expect(endpointJson).toContain("token=%5BREDACTED%5D");
expect(endpointJson).not.toContain("fixture-secret");
};
const fixtureDirectory = async (): Promise<string> => {
const root = await createTestTempDirectory("rea-javascript-artifact-");
await writeJavaScriptArtifactFixture(root);
return root;
};
@@ -0,0 +1,344 @@
import { Readable } from "node:stream";
import { symlink, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { readJavaScriptArtifactFiles } from "../../../src/application/JavaScriptArtifactFiles.js";
import { reconstructJavaScriptArtifact } from "../../../src/application/JavaScriptArtifactReconstruction.js";
import {
artifactLimitsForReconstruction,
javascriptArtifactReconstructionInputSchema,
} from "../../../src/application/JavaScriptArtifactReconstructionInput.js";
import { scanArtifactInventory } from "../../../src/application/ArtifactInventory.js";
import {
type ArtifactEntry,
type ArtifactReader,
} from "../../../src/artifacts/ArtifactReader.js";
import { writeJavaScriptArtifactFixture } from "../../fixtures/javascriptArtifactApplication.js";
it("discovers source maps without reading them until separately approved", async () => {
const root = await fixtureDirectory();
const unapproved = await reconstructJavaScriptArtifact({
input_path: root,
source_map_read_approved: false,
});
const approved = await reconstructJavaScriptArtifact({
input_path: root,
source_map_read_approved: true,
});
expect(unapproved.graph.nodes.some(({ kind }) => kind === "source-map")).toBe(
true,
);
expect(
unapproved.graph.nodes.some(({ kind }) => kind === "source-module"),
).toBe(false);
expect(unapproved.graph.coverage).toMatchObject({
status: "partial",
truncated: false,
omitted_count: null,
});
expect(unapproved.statistics.policy_filtered_text_files).toBe(1);
expect(unapproved.graph.nodes).toEqual(
expect.arrayContaining([
expect.objectContaining({
kind: "unknown",
observations: expect.arrayContaining([
expect.objectContaining({
properties: expect.objectContaining({
operation: "parse-local-source-map",
}),
evidence: expect.objectContaining({ state: "unavailable" }),
}),
]),
}),
]),
);
expect(
approved.graph.nodes.some(({ kind }) => kind === "source-module"),
).toBe(true);
});
it("reports text and AST limits as truncation instead of absence", async () => {
const root = await fixtureDirectory();
const result = await reconstructJavaScriptArtifact({
input_path: root,
source_map_read_approved: true,
limits: {
max_text_file_bytes: 128,
max_total_text_bytes: 1_024,
max_ast_nodes: 50,
},
});
expect(result.statistics.limit_omitted_text_files).toBeGreaterThan(0);
expect(result.graph.coverage).toMatchObject({
status: "partial",
truncated: true,
});
expect(result.graph.coverage.omitted_count).toBeGreaterThan(0);
expect(result.graph.nodes.some(({ kind }) => kind === "unknown")).toBe(true);
expect(result.graph.limitations.join(" ")).toMatch(/incomplete|bound/iu);
});
it("uses an unknown omission count when AST traversal reaches its bound", async () => {
const root = await createTestTempDirectory("rea-javascript-ast-limit-");
await writeFile(
join(root, "large.js"),
[
'import "./unobserved.js";',
...Array.from(
{ length: 100 },
(_, index) => `export const value${String(index)} = ${String(index)};`,
),
].join("\n"),
);
const result = await reconstructJavaScriptArtifact({
input_path: root,
limits: { max_ast_nodes: 50 },
});
expect(result.statistics.limit_omitted_text_files).toBe(0);
expect(result.statistics.truncated_scopes).toBe(1);
expect(result.graph.coverage).toMatchObject({
status: "partial",
truncated: true,
omitted_count: null,
});
const derivedImport = result.graph.edges.find(
({ relation, properties }) =>
relation === "imports" && properties.specifier === "./unobserved.js",
);
expect(derivedImport?.evidence.coverage).toEqual({
status: "partial",
truncated: true,
omitted_count: null,
limits: expect.arrayContaining([
{ name: "max-ast-nodes", value: 50, unit: "items" },
]),
});
});
it("does not follow symlinks or read oversized JavaScript text", async () => {
const root = await fixtureDirectory();
const outside = await createTestTempDirectory("rea-javascript-outside-");
const outsideFile = join(outside, "secret.js");
await writeFile(
outsideFile,
'fetch("https://outside-secret.invalid/credential");',
);
await symlink(outsideFile, join(root, "escape.js"));
await writeFile(
join(root, "oversized.js"),
`const oversizedSecret = "${"private-marker-".repeat(256)}";`,
);
const result = await reconstructJavaScriptArtifact({
input_path: root,
limits: { max_text_file_bytes: 512 },
});
const encoded = JSON.stringify(result);
expect(result.statistics.limit_omitted_text_files).toBeGreaterThan(0);
expect(result.graph.coverage).toMatchObject({
status: "partial",
truncated: true,
});
expect(encoded).not.toContain(outsideFile);
expect(encoded).not.toContain("outside-secret.invalid");
expect(encoded).not.toContain("private-marker-private-marker");
});
it("keeps malformed JavaScript, package metadata, and source maps as explicit unknowns", async () => {
const root = await fixtureDirectory();
await Promise.all([
writeFile(join(root, "package.json"), "{"),
writeFile(join(root, "broken.js"), "function broken( {"),
writeFile(join(root, "renderer", "renderer.js.map"), "{"),
]);
const result = await reconstructJavaScriptArtifact({
input_path: root,
source_map_read_approved: true,
});
const unknownOperations = result.graph.nodes
.filter(({ kind }) => kind === "unknown")
.flatMap(({ observations }) =>
observations.map(({ properties }) => properties.operation),
);
expect(result.statistics.parse_failures).toBeGreaterThan(0);
expect(result.graph.coverage).toMatchObject({
status: "partial",
truncated: false,
omitted_count: null,
});
expect(unknownOperations).toEqual(
expect.arrayContaining([
"parse-javascript",
"parse-package-json",
"parse-local-source-map",
]),
);
});
it("applies one source-map source budget across every local map", async () => {
const root = await createTestTempDirectory("rea-javascript-source-maps-");
await Promise.all([
writeFile(
join(root, "a.js.map"),
JSON.stringify({
version: 3,
sources: ["a-one.ts", "a-two.ts"],
sourcesContent: ["one", "two"],
names: [],
mappings: "",
}),
),
writeFile(
join(root, "b.js.map"),
JSON.stringify({
version: 3,
sources: ["b-one.ts", "b-two.ts"],
sourcesContent: ["three", "four"],
names: [],
mappings: "",
}),
),
]);
const result = await reconstructJavaScriptArtifact({
input_path: root,
source_map_read_approved: true,
limits: { max_source_map_sources: 3 },
});
expect(
result.graph.nodes.filter(({ kind }) => kind === "source-module"),
).toHaveLength(3);
expect(result.graph.coverage).toMatchObject({
status: "partial",
truncated: true,
omitted_count: null,
});
});
it("bounds repeated content observations while retaining every containment path", async () => {
const root = await createTestTempDirectory("rea-javascript-observations-");
await Promise.all(
Array.from({ length: 70 }, (_, index) =>
writeFile(
join(root, `duplicate-${String(index).padStart(2, "0")}.js`),
"export const same = 1;\n",
),
),
);
const result = await reconstructJavaScriptArtifact({ input_path: root });
const duplicateNode = result.graph.nodes.find(
({ kind, observations }) =>
kind === "javascript-asset" &&
observations.some(({ properties }) =>
String(properties.path).startsWith("duplicate-"),
),
);
const duplicateEdges = result.graph.edges.filter(
({ relation, properties }) =>
relation === "contains" &&
String(properties.path).startsWith("duplicate-"),
);
expect(duplicateNode?.observations).toHaveLength(64);
expect(duplicateEdges).toHaveLength(70);
expect(result.graph.coverage).toMatchObject({
status: "partial",
truncated: true,
omitted_count: 6,
});
}, 15_000);
it("rejects traversal from a production reader seam and malformed ASAR containers", async () => {
const root = await fixtureDirectory();
const input = javascriptArtifactReconstructionInputSchema.parse({
input_path: root,
});
const snapshot = await scanArtifactInventory(
root,
artifactLimitsForReconstruction(input),
);
await expect(
readJavaScriptArtifactFiles(new TraversalReader(), snapshot, input),
).rejects.toMatchObject({ reason: "path" });
const malformed = join(root, "malformed.asar");
await writeFile(malformed, "not an asar");
await expect(
reconstructJavaScriptArtifact({ input_path: malformed }),
).rejects.toMatchObject({
name: "ArtifactReaderFailure",
reason: "format",
});
});
it("preserves cancellation and explicit format diagnostics", async () => {
const root = await fixtureDirectory();
const controller = new AbortController();
controller.abort();
await expect(
reconstructJavaScriptArtifact({ input_path: root }, controller.signal),
).rejects.toMatchObject({ reason: "cancelled" });
await expect(
reconstructJavaScriptArtifact({ input_path: root, format: "asar" }),
).rejects.toMatchObject({
reason: "format",
message: expect.stringContaining(root),
});
expect(() =>
javascriptArtifactReconstructionInputSchema.parse({
input_path: root,
limits: { max_entries: 100_000 },
}),
).toThrow(/graph contract/iu);
});
class TraversalReader implements ArtifactReader {
readonly format = "directory" as const;
async *entries(): AsyncIterable<ArtifactEntry> {
yield {
path: "../escape.js",
kind: "file",
declaredSize: 1,
compressedSize: null,
executable: false,
encrypted: false,
byteOffset: null,
declaredSha256: null,
unpacked: false,
limitations: [],
adapterKey: "/tmp/escape.js",
};
}
open(): Promise<Readable> {
return Promise.resolve(Readable.from("x"));
}
close(): Promise<void> {
return Promise.resolve();
}
provenance(): readonly [] {
return [];
}
}
const fixtureDirectory = async (): Promise<string> => {
const root = await createTestTempDirectory("rea-javascript-artifact-");
await writeJavaScriptArtifactFixture(root);
return root;
};
@@ -0,0 +1,264 @@
import { mkdir, rm, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { reconstructJavaScriptArtifact } from "../../../src/application/JavaScriptArtifactReconstruction.js";
import type {
ApplicationEdge,
ApplicationNode,
JavaScriptApplicationGraph,
} from "../../../src/domain/javascriptApplicationGraph.js";
describe("Webpack and Rspack runtime adapters", () => {
it("recovers runtime entry modules, async chunks, and factory require aliases", async () => {
const root = await bundlerFixture();
try {
const result = await reconstructJavaScriptArtifact({ input_path: root });
const graph = result.graph;
const webpackEntry = chunk(graph, "webpackChunkcustomPortal", "main");
const webpackLazy = chunk(graph, "webpackChunkcustomPortal", "lazy");
const webpackModule = moduleNode(graph, "10");
const rspackEntry = chunk(graph, "rspackChunkcustomPortal", "editor");
const rspackModel = chunk(graph, "rspackChunkcustomPortal", "model");
const rspackModule = moduleNode(graph, "src/entry.ts");
expect(webpackEntry?.observations[0]?.properties).toMatchObject({
bundler: "webpack",
runtime_require_name: "__webpack_require__",
runtime_module_cache_status: "observed",
entry_module_keys: ["10"],
async_chunk_keys: ["lazy", "missing"],
unknown_async_chunk_keys: 1,
});
expect(webpackModule?.observations[0]?.properties).toMatchObject({
factory_require_name: "__webpack_require__",
runtime_entry: true,
chunk_keys: ["main"],
});
expect(rspackEntry?.observations[0]?.properties).toMatchObject({
bundler: "rspack",
runtime_require_name: "r",
entry_module_keys: ["src/entry.ts"],
async_chunk_keys: ["model"],
});
expect(rspackModule?.observations[0]?.properties).toMatchObject({
factory_require_name: "r",
runtime_entry: true,
});
expect(edge(graph, webpackEntry, webpackModule, "loads")).toMatchObject({
properties: expect.objectContaining({
kind: "bundler-entry-module",
resolution_status: "resolved",
}),
});
expect(edge(graph, webpackEntry, webpackLazy, "imports")).toMatchObject({
properties: expect.objectContaining({
kind: "bundler-async-chunk",
resolution_status: "resolved",
}),
});
expect(edge(graph, webpackModule, webpackLazy, "imports")).toMatchObject({
properties: expect.objectContaining({
kind: "dynamic-import",
specifier: "chunk:lazy",
resolved_path: "renderer/chunks/runtime.js#chunk:lazy",
}),
});
expect(edge(graph, rspackEntry, rspackModel, "imports")).toMatchObject({
properties: expect.objectContaining({
kind: "bundler-async-chunk",
resolution_status: "resolved",
}),
});
expect(edge(graph, rspackModule, rspackModel, "imports")).toMatchObject({
properties: expect.objectContaining({
kind: "dynamic-import",
specifier: "chunk:model",
}),
});
expect(
graph.nodes.find((node) =>
node.observations.some(
({ properties }) =>
properties.semantic_role === "bundler-chunk-reference" &&
properties.chunk_key === "missing" &&
properties.resolution_status === "not-found",
),
),
).toBeDefined();
expect(
graph.edges.some(
({ relation, properties }) =>
relation === "imports" &&
properties.kind === "require" &&
properties.specifier === "lazy",
),
).toBe(false);
} finally {
await rm(root, { recursive: true, force: true });
}
});
it("recovers esbuild wrapper modules and Vite preload dependencies", async () => {
const root = await esmRuntimeFixture();
try {
const { graph } = await reconstructJavaScriptArtifact({
input_path: root,
});
const commonJsModule = moduleNode(graph, "src/dep.js");
const esmModule = moduleNode(graph, "src/core.js");
expect(commonJsModule?.observations[0]?.properties).toMatchObject({
bundler: "esbuild",
runtime: "esbuild-commonjs",
module_key: "src/dep.js",
});
expect(esmModule?.observations[0]?.properties).toMatchObject({
bundler: "esbuild",
runtime: "esbuild-esm",
module_key: "src/core.js",
});
expect(
graph.edges.filter(
({ relation, properties }) =>
relation === "imports" &&
properties.kind === "dynamic-import" &&
["./feature.js", "./main.css"].includes(
String(properties.specifier),
),
),
).toHaveLength(2);
} finally {
await rm(root, { recursive: true, force: true });
}
});
});
const bundlerFixture = async (): Promise<string> => {
const root = await createTestTempDirectory("rea-bundler-adapters-");
await mkdir(join(root, "renderer", "chunks"), { recursive: true });
await writeFile(
join(root, "renderer", "chunks", "runtime.js"),
`
var __webpack_module_cache__ = {};
(globalThis["webpackChunkcustomPortal"] = globalThis["webpackChunkcustomPortal"] || []).push([
["main"],
{
10: (module, exports, __webpack_require__) => {
const direct = __webpack_require__(11);
const lazy = __webpack_require__.e("lazy").then(
__webpack_require__.bind(__webpack_require__, 20)
);
const missing = __webpack_require__.e("missing");
const dynamicChunk = window.name;
__webpack_require__.e(dynamicChunk);
exports.start = () => [direct, lazy, missing];
},
11: (module) => { module.exports = "direct"; }
},
(__webpack_require__) => {
__webpack_require__.O(0, ["main"], () => __webpack_require__(10));
}
]);
(globalThis["webpackChunkcustomPortal"] = globalThis["webpackChunkcustomPortal"] || []).push([
["lazy"],
{
20: (module) => { module.exports = "lazy"; }
}
]);
(self.rspackChunkcustomPortal = self.rspackChunkcustomPortal || []).push([
["editor"],
{
"src/entry.ts": (module, exports, r) => {
r.e("model").then(r.bind(r, "src/model.ts"));
exports.render = () => r("src/model.ts");
}
},
(r) => { r("src/entry.ts"); }
]);
(self.rspackChunkcustomPortal = self.rspackChunkcustomPortal || []).push([
["model"],
{
"src/model.ts": (module) => { module.exports = "model"; }
}
]);
`,
);
return root;
};
const esmRuntimeFixture = async (): Promise<string> => {
const root = await createTestTempDirectory("rea-esm-runtime-adapters-");
await writeFile(
join(root, "main.js"),
`
const __vite__mapDeps = (indexes, map = __vite__mapDeps, dependencies =
(map.f || (map.f = ["./feature.js", "./main.css"]))) =>
indexes.map((index) => dependencies[index]);
const require_dep = __commonJS({
"src/dep.js"(exports, module) {
module.exports = { value: 1 };
}
});
const init_core = __esm({
"src/core.js"() {
require_dep();
}
});
__vite__mapDeps([0, 1]);
init_core();
`,
);
await writeFile(join(root, "feature.js"), "export const feature = true;");
await writeFile(join(root, "main.css"), ".app { color: green; }");
return root;
};
const chunk = (
graph: JavaScriptApplicationGraph,
runtime: string,
chunkKey: string,
): ApplicationNode | undefined =>
graph.nodes.find(
({ kind, observations }) =>
kind === "javascript-chunk" &&
observations.some(
({ properties }) =>
properties.runtime === runtime &&
Array.isArray(properties.chunk_keys) &&
properties.chunk_keys.includes(chunkKey),
),
);
const moduleNode = (
graph: JavaScriptApplicationGraph,
moduleKey: string,
): ApplicationNode | undefined =>
graph.nodes.find(
({ kind, observations }) =>
kind === "javascript-module" &&
observations.some(
({ properties }) => properties.module_key === moduleKey,
),
);
const edge = (
graph: JavaScriptApplicationGraph,
source: ApplicationNode | undefined,
target: ApplicationNode | undefined,
relation: string,
): ApplicationEdge | undefined =>
graph.edges.find(
({ source_node_id, target_node_id, relation: edgeRelation }) =>
source !== undefined &&
target !== undefined &&
source_node_id === source.node_id &&
target_node_id === target.node_id &&
edgeRelation === relation,
);
@@ -0,0 +1,83 @@
import { createHash } from "node:crypto";
import { describe, expect, it } from "vitest";
import { instrumentJavaScriptExport } from "../../../src/domain/javascriptExportInstrumentation.js";
const encode = (value: string): Uint8Array => new TextEncoder().encode(value);
const sha256 = (value: Uint8Array): string =>
createHash("sha256").update(value).digest("hex");
describe("JavaScript export instrumentation", () => {
it.each([
[
"plain",
"const hidden = (value) => value.trim();",
"(value) => value.trim()",
],
["minified", "const x=a=>a+1,y=2;", "a=>a+1"],
[
"bundle",
"(()=>{const registry={7:(m)=>m.exports=(x)=>x*2};globalThis.r=registry})()",
"(x)=>x*2",
],
])(
"deterministically exposes one exact %s expression",
(_name, text, selectedText) => {
const source = encode(text);
const original = source.slice();
const start = text.indexOf(selectedText);
const selected = encode(selectedText);
const input = {
artifact_path: "/approved/app.js",
artifact_sha256: sha256(source),
selection: {
byte_start: start,
byte_end: start + selected.byteLength,
selected_sha256: sha256(selected),
export_name: "selected",
},
};
const first = instrumentJavaScriptExport(source, input);
const second = instrumentJavaScriptExport(source, input);
expect(first).toEqual(second);
expect(source).toEqual(original);
expect(first.manifest).toMatchObject({
original_sha256: sha256(source),
instrumented_sha256: sha256(first.bytes),
output_format: "commonjs-factory",
inserted_ranges: [
{ purpose: "factory-prefix" },
{ purpose: "export-binding" },
{ purpose: "factory-suffix" },
],
});
},
);
it("rejects stale artifacts and ambiguous caller-selected bytes", () => {
const source = encode("const hidden = () => 1;");
const input = {
artifact_path: "/approved/app.js",
artifact_sha256: "0".repeat(64),
selection: {
byte_start: 15,
byte_end: 22,
selected_sha256: "1".repeat(64),
export_name: "hidden",
},
};
expect(() => instrumentJavaScriptExport(source, input)).toThrow(
/artifact digest mismatch/u,
);
expect(() =>
instrumentJavaScriptExport(source, {
...input,
artifact_sha256: sha256(source),
}),
).toThrow(/selection digest mismatch/u);
});
});
@@ -0,0 +1,336 @@
import { copyFile, mkdir, rm, writeFile } from "node:fs/promises";
import { join, resolve } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { analyzeJavaScriptApplication } from "../../../src/application/JavaScriptApplicationService.js";
import { parseApplicationGraphEvidence } from "../../../src/application/JavaScriptApplicationEvidenceGraph.js";
import { compareJavaScriptExportShapes } from "../../../src/domain/javascriptExportShapeComparison.js";
import { javaScriptExportShapeComparisonResultSchema } from "../../../src/domain/javascriptExportShapeComparisonSchemas.js";
import {
createJavaScriptApplicationGraph,
createJavaScriptApplicationNode,
} from "../../../src/domain/javascriptApplicationGraph.js";
import { permissionAuthorityForRoot } from "../../fixtures/permissionAuthority.js";
const temporary: string[] = [];
afterEach(async () => {
await Promise.all(
temporary
.splice(0)
.map(async (path) => rm(path, { recursive: true, force: true })),
);
});
describe("JavaScript export return-shape comparison", () => {
it("reports exactly the heading depth addition from source-owned parser fixtures", async () => {
const root = await temporaryRoot(temporary);
const leftRoot = join(root, "left");
const rightRoot = join(root, "right");
await Promise.all([mkdir(leftRoot), mkdir(rightRoot)]);
await Promise.all([
copyFile(
resolve("tests/fixtures/replay/parser.mjs"),
join(leftRoot, "parser.mjs"),
),
copyFile(
resolve("tests/fixtures/replay/parser-v2.mjs"),
join(rightRoot, "parser.mjs"),
),
]);
const [left, right] = await Promise.all([
analyzeGraph(leftRoot),
analyzeGraph(rightRoot),
]);
const first = compare(left, right);
const second = compare(left, right);
expect(first.comparison_id).toBe(second.comparison_id);
expect(() =>
javaScriptExportShapeComparisonResultSchema.parse(first),
).not.toThrow();
expect(first.summary).toEqual({
added: 1,
removed: 0,
changed: 0,
unknown: 0,
});
expect(first.changes).toEqual([
expect.objectContaining({
status: "added",
path: "/depth",
discriminant: { path: "/type", value: "heading" },
left: { availability: "absent" },
right: { availability: "literal", value: 1 },
}),
]);
expect(first.changes.some(({ path }) => path === "/text")).toBe(false);
expect(first.coverage).toMatchObject({
status: "complete-within-inputs",
paired_variants: 3,
unpaired_left_variants: 0,
unpaired_right_variants: 0,
});
expect(first.runtime_validation).toEqual({
recommended_tool: "run_controlled_replay",
automatically_started: false,
required_for: "runtime-semantics",
});
});
it("keeps additions unknown when spread coverage is incomplete", async () => {
const [left, right] = await analyzeSources(temporary, {
left: `
const dynamic = getDynamic();
export default () => ({ type: "heading", ...dynamic });
`,
right: `
const dynamic = getDynamic();
export default () => ({ type: "heading", depth: 1, ...dynamic });
`,
});
const result = compare(left, right);
expect(result.changes).toEqual([
expect.objectContaining({ status: "unknown", path: "/depth" }),
]);
expect(result.coverage.status).toBe("partial");
});
it("does not pair ambiguous variants or invent behavior for no-return exports", async () => {
const ambiguous = await analyzeSources(temporary, {
left: `
export default function parse(value) {
if (value) return { type: "heading", text: render(value) };
return { type: "heading", text: render(value) };
}
`,
right: `export default (value) => ({ type: "heading", text: render(value) });`,
});
const compared = compare(...ambiguous);
expect(compared.summary.unknown).toBe(3);
expect(compared.coverage).toMatchObject({
status: "partial",
paired_variants: 0,
unpaired_left_variants: 2,
unpaired_right_variants: 1,
});
const noReturn = await analyzeSources(temporary, {
left: `export default function stop() { throw new Error("stop"); }`,
right: `export default function stop() { throw new Error("stop"); }`,
});
const unknown = compare(...noReturn);
expect(unknown.changes).toEqual([
expect.objectContaining({ status: "unknown", path: "" }),
]);
});
});
describe("JavaScript export return-shape selection", () => {
it("reports selector candidates and enforces candidate, variant, and change limits", async () => {
const candidates = await analyzeSources(temporary, {
left: `
export const first = () => ({ type: "first" });
export const second = () => ({ type: "second" });
export const third = () => ({ type: "third" });
`,
right: `export default () => ({ type: "default" });`,
});
const missing = compare(candidates[0], candidates[1], {
leftExportName: "missing",
limits: { max_candidate_exports: 1 },
});
expect(missing.left).toMatchObject({
status: "missing",
omitted_candidates: 2,
candidates: [expect.objectContaining({ module_path: "parser.mjs" })],
});
expect(missing.coverage.status).toBe("truncated");
const parsers = await sourceOwnedParsers(temporary);
const variantLimited = compare(parsers[0], parsers[1], {
limits: { max_return_variants: 1 },
});
expect(variantLimited.coverage).toMatchObject({
status: "truncated",
omitted_left_variants: 2,
omitted_right_variants: 2,
});
const changes = await analyzeSources(temporary, {
left: `export default () => ({ type: "item" });`,
right: `export default () => ({ type: "item", depth: 1, level: 2 });`,
});
const changeLimited = compare(changes[0], changes[1], {
limits: { max_changes: 1 },
});
expect(changeLimited.summary.added).toBe(2);
expect(changeLimited.changes).toHaveLength(1);
expect(changeLimited.coverage).toMatchObject({
status: "truncated",
omitted_changes: 1,
});
});
it("refuses an exact selector that resolves to multiple graph nodes", async () => {
const [left, right] = await analyzeSources(temporary, {
left: `export default () => ({ type: "item" });`,
right: `export default () => ({ type: "item" });`,
});
const exported = left.graph.nodes.find((node) =>
node.observations.some(
({ properties }) => properties.semantic_role === "export-binding",
),
);
if (
exported === undefined ||
exported.identity.strategy !== "artifact-local-key"
)
throw new Error("Expected one artifact-local export fixture node");
const duplicate = createJavaScriptApplicationNode({
kind: exported.kind,
identity: {
...exported.identity,
key: `${exported.identity.key}:duplicate`,
},
observations: exported.observations.map(
({ label, properties, evidence }) => ({ label, properties, evidence }),
),
});
const ambiguousGraph = createJavaScriptApplicationGraph({
schema: "JavaScriptApplicationGraph",
schema_version: 1,
root_node_ids: left.graph.root_node_ids,
nodes: [...left.graph.nodes, duplicate],
edges: left.graph.edges,
coverage: left.graph.coverage,
limitations: left.graph.limitations,
});
const result = compare({ ...left, graph: ambiguousGraph }, right);
expect(result.left).toMatchObject({
status: "ambiguous",
selected_node_id: null,
candidates: [expect.any(Object), expect.any(Object)],
});
expect(result.changes).toEqual([
expect.objectContaining({ status: "unknown", path: "" }),
]);
});
});
describe("JavaScript export return-shape projection", () => {
it("marks graph field projection omissions as truncated", async () => {
const properties = [
'a_type: "item"',
...Array.from(
{ length: 70 },
(_, index) => `field${String(index)}: ${String(index)}`,
),
].join(",");
const [left, right] = await analyzeSources(temporary, {
left: `export default () => ({ ${properties} });`,
right: `export default () => ({ ${properties} });`,
});
const result = compare(left, right);
expect(result.coverage.status).toBe("truncated");
expect(result.coverage.left_omitted_fields).toBeGreaterThan(0);
expect(result.coverage.right_omitted_fields).toBeGreaterThan(0);
});
});
type GraphSource = Awaited<ReturnType<typeof analyzeGraph>>;
const compare = (
left: GraphSource,
right: GraphSource,
options: {
readonly leftExportName?: string;
readonly rightExportName?: string;
readonly limits?: Partial<{
readonly max_candidate_exports: number;
readonly max_return_variants: number;
readonly max_changes: number;
}>;
} = {},
) =>
compareJavaScriptExportShapes({
left: {
evidenceId: left.evidence.evidence_id,
graph: left.graph,
modulePath: "parser.mjs",
exportName: options.leftExportName ?? "default",
},
right: {
evidenceId: right.evidence.evidence_id,
graph: right.graph,
modulePath: "parser.mjs",
exportName: options.rightExportName ?? "default",
},
limits: {
max_candidate_exports: options.limits?.max_candidate_exports ?? 100,
max_return_variants: options.limits?.max_return_variants ?? 128,
max_changes: options.limits?.max_changes ?? 1_000,
},
});
const analyzeGraph = async (root: string) => {
const authority = await permissionAuthorityForRoot(
root,
["investigation_input"],
["investigation_input"],
);
const result = await analyzeJavaScriptApplication(authority, {
input_path: root,
approved: true,
});
if (!result.ok) throw result.error;
return parseApplicationGraphEvidence(result.value);
};
const analyzeSources = async (
temporary: string[],
sources: { readonly left: string; readonly right: string },
): Promise<[GraphSource, GraphSource]> => {
const root = await temporaryRoot(temporary);
const leftRoot = join(root, "left");
const rightRoot = join(root, "right");
await Promise.all([mkdir(leftRoot), mkdir(rightRoot)]);
await Promise.all([
writeFile(join(leftRoot, "parser.mjs"), sources.left),
writeFile(join(rightRoot, "parser.mjs"), sources.right),
]);
return Promise.all([analyzeGraph(leftRoot), analyzeGraph(rightRoot)]);
};
const sourceOwnedParsers = async (
temporary: string[],
): Promise<[GraphSource, GraphSource]> => {
const root = await temporaryRoot(temporary);
const leftRoot = join(root, "left");
const rightRoot = join(root, "right");
await Promise.all([mkdir(leftRoot), mkdir(rightRoot)]);
await Promise.all([
copyFile(
resolve("tests/fixtures/replay/parser.mjs"),
join(leftRoot, "parser.mjs"),
),
copyFile(
resolve("tests/fixtures/replay/parser-v2.mjs"),
join(rightRoot, "parser.mjs"),
),
]);
return Promise.all([analyzeGraph(leftRoot), analyzeGraph(rightRoot)]);
};
const temporaryRoot = async (temporary: string[]): Promise<string> => {
const root = await createTestTempDirectory("rea-export-shapes-");
temporary.push(root);
return root;
};
@@ -0,0 +1,310 @@
import { mkdir, rm, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { reconstructJavaScriptArtifact } from "../../../src/application/JavaScriptArtifactReconstruction.js";
import type {
ApplicationEdge,
ApplicationNode,
JavaScriptApplicationGraph,
} from "../../../src/domain/javascriptApplicationGraph.js";
describe("CommonJS and ESM module relationships", () => {
it("composes bindings, re-exports, dynamic imports, and JSON modules", async () => {
const root = await moduleFixture();
try {
const first = await reconstructJavaScriptArtifact({ input_path: root });
const second = await reconstructJavaScriptArtifact({ input_path: root });
const graph = first.graph;
expect(second.graph).toEqual(graph);
expect(sourceModule(graph, "main.cjs")).toBeDefined();
expect(sourceModule(graph, "consumer.mjs")).toBeDefined();
expect(sourceModule(graph, "dependency.mjs")).toBeDefined();
expect(
relationship(graph, {
kind: "require",
specifier: "./dependency.mjs",
resolvedPath: "dependency.mjs",
importedName: "value",
localName: "importedValue",
}),
).toBeDefined();
expect(
graph.edges.filter(
({ relation, properties }) =>
relation === "imports" &&
properties.specifier === "fixture-package",
),
).not.toEqual(
expect.arrayContaining([
expect.objectContaining({
properties: expect.objectContaining({ resolved_path: null }),
}),
]),
);
expect(
relationship(graph, {
kind: "require",
specifier: "fixture-package",
resolvedPath: "node_modules/fixture-package/cjs.cjs",
localName: "packageValue",
}),
).toBeDefined();
expect(
relationship(graph, {
kind: "import",
specifier: "fixture-package",
resolvedPath: "node_modules/fixture-package/esm.mjs",
importedName: "default",
localName: "packageDefault",
}),
).toBeDefined();
expect(
relationship(graph, {
kind: "import",
specifier: "./values.js",
resolvedPath: "values.js",
importedName: "value",
localName: "alias",
}),
).toBeDefined();
expect(
relationship(graph, {
kind: "re-export",
specifier: "./star.js",
resolvedPath: "star.js",
importedName: "*",
exportedName: "*",
}),
).toBeDefined();
const forwarded = exportNode(graph, "main.cjs", "forwarded");
expect(forwarded).toBeDefined();
expect(
graph.edges.some(
({ source_node_id, relation, properties }) =>
source_node_id === forwarded?.node_id &&
relation === "imports" &&
properties.resolved_path === "dependency.mjs" &&
properties.imported_name === "value",
),
).toBe(true);
expect(
graph.edges.find(
({ relation, properties }) =>
relation === "imports" &&
properties.kind === "dynamic-import" &&
properties.resolved_path === "lazy.js",
),
).toMatchObject({
source_node_id: sourceModule(graph, "consumer.mjs")?.node_id,
});
expect(
relationship(graph, {
kind: "require",
specifier: "./data.json",
resolvedPath: "data.json",
})?.properties,
).toMatchObject({
target_file_kind: "json",
target_json_status: "included",
});
expect(
relationship(graph, {
kind: "require",
specifier: "./broken.json",
resolvedPath: "broken.json",
})?.properties,
).toMatchObject({
target_file_kind: "json",
target_json_status: "invalid",
});
expect(
relationship(graph, {
kind: "require",
specifier: "electron",
})?.properties,
).toMatchObject({ resolution_status: "external", resolved_path: null });
expect(
graph.edges.find(
({ relation, properties }) =>
relation === "imports" &&
properties.kind === "require" &&
properties.specifier === null,
)?.properties,
).toMatchObject({ resolved_path: null });
expect(first.statistics.parse_failures).toBe(1);
expect(graph.coverage).toMatchObject({
status: "partial",
truncated: false,
});
expect(graph.limitations.join(" ")).toMatch(/incomplete/iu);
} finally {
await rm(root, { recursive: true, force: true });
}
});
});
describe("CommonJS and ESM relationship limits", () => {
it("retains exact semantic omissions when the relationship budget truncates", async () => {
const root = await createTestTempDirectory("rea-module-limit-");
try {
await writeFile(
join(root, "exports.mjs"),
"export const first = 1; export const second = 2; export const third = 3;",
);
const result = await reconstructJavaScriptArtifact({
input_path: root,
limits: { max_findings: 1 },
});
expect(result.statistics.truncated_scopes).toBeGreaterThan(0);
expect(
result.graph.nodes.filter((node) =>
node.observations.some(
({ properties }) => properties.semantic_role === "export-binding",
),
),
).toHaveLength(1);
expect(result.graph.coverage).toMatchObject({
status: "partial",
truncated: true,
omitted_count: 2,
});
} finally {
await rm(root, { recursive: true, force: true });
}
});
});
const moduleFixture = async (): Promise<string> => {
const root = await createTestTempDirectory("rea-module-relationships-");
await mkdir(join(root, "node_modules", "fixture-package"), {
recursive: true,
});
await Promise.all([
writeFile(join(root, "package.json"), '{"main":"main.cjs"}'),
writeFile(
join(root, "main.cjs"),
`
const { value: importedValue } = require("./dependency.mjs");
const data = require("./data.json");
const broken = require("./broken.json");
const electron = require("electron");
const packageValue = require("fixture-package");
module.exports.forwarded = importedValue;
exports.data = data;
exports.broken = broken;
exports.electron = electron;
exports.packageValue = packageValue;
require(dynamicName);
`,
),
writeFile(
join(root, "dependency.mjs"),
`
export { value } from "./values.js";
export * from "./star.js";
`,
),
writeFile(
join(root, "consumer.mjs"),
`
import { value as alias } from "./values.js";
import packageDefault from "fixture-package";
export { alias as relayed };
void import("./lazy.js");
void packageDefault;
`,
),
writeFile(join(root, "values.js"), "export const value = 42;"),
writeFile(join(root, "star.js"), "export const extra = true;"),
writeFile(join(root, "lazy.js"), "export default 'lazy';"),
writeFile(join(root, "data.json"), '{"name":"fixture","value":42}'),
writeFile(join(root, "broken.json"), '{"name":'),
writeFile(
join(root, "node_modules", "fixture-package", "package.json"),
JSON.stringify({
exports: {
".": {
import: "./esm.mjs",
require: "./cjs.cjs",
},
},
}),
),
writeFile(
join(root, "node_modules", "fixture-package", "esm.mjs"),
"export default 'esm';",
),
writeFile(
join(root, "node_modules", "fixture-package", "cjs.cjs"),
"module.exports = 'cjs';",
),
]);
return root;
};
interface RelationshipQuery {
readonly kind: string;
readonly specifier: string;
readonly resolvedPath?: string;
readonly importedName?: string;
readonly localName?: string;
readonly exportedName?: string;
}
const relationship = (
graph: JavaScriptApplicationGraph,
query: RelationshipQuery,
): ApplicationEdge | undefined =>
graph.edges.find(
({ relation, properties }) =>
relation === "imports" &&
properties.module_link_kind === query.kind &&
properties.specifier === query.specifier &&
(query.resolvedPath === undefined ||
properties.resolved_path === query.resolvedPath) &&
(query.importedName === undefined ||
properties.imported_name === query.importedName) &&
(query.localName === undefined ||
properties.local_name === query.localName) &&
(query.exportedName === undefined ||
properties.exported_name === query.exportedName),
);
const sourceModule = (
graph: JavaScriptApplicationGraph,
path: string,
): ApplicationNode | undefined =>
graph.nodes.find(
(node) =>
node.kind === "javascript-module" &&
node.observations.some(
({ properties }) => properties.logical_module_key === path,
),
);
const exportNode = (
graph: JavaScriptApplicationGraph,
path: string,
name: string,
): ApplicationNode | undefined =>
graph.nodes.find(
(node) =>
node.kind === "javascript-module" &&
node.observations.some(
({ properties }) =>
properties.semantic_role === "export-binding" &&
properties.module_path === path &&
properties.exported_name === name,
),
);
@@ -0,0 +1,241 @@
import { it } from "@fast-check/vitest";
import { describe, expect } from "vitest";
import { analyzeJavaScriptSemantics } from "../../../src/domain/javascriptSemanticAnalysis.js";
import { semanticBinding } from "../../../src/domain/javascriptSemanticIr.js";
import {
onlyCallable,
topLevelBinding,
} from "./javascriptSemanticAnalysis.support.js";
describe("JavaScript semantic analysis: calls 1", () => {
it("links exact local calls to parameters, returns, and closure captures", () => {
const ir = analyzeJavaScriptSemantics(`
const prefix = "rea";
function render(value, { mode }) {
return prefix + value + mode;
}
const alias = render;
const result = alias(input, { mode: "fast" });
`);
expect(ir.schemaVersion).toBe(4);
const render = onlyCallable(ir, "render");
const call = ir.callSites.find(
({ calleeCallableIds }) => calleeCallableIds[0] === render.callableId,
);
expect(call).toMatchObject({
kind: "call",
callerCallableId: null,
resolution: "exact",
calleeCallableIds: [render.callableId],
arguments: [
{ index: 0, spread: false },
{ index: 1, spread: false },
],
});
if (call === undefined) throw new Error("Missing render call");
expect(
ir.argumentFlows
.filter(({ callSiteId }) => callSiteId === call.callSiteId)
.map(({ argumentIndex, parameterBindingId }) => ({
argumentIndex,
parameter: semanticBinding(ir, parameterBindingId)?.name,
})),
).toEqual([
{ argumentIndex: 0, parameter: "value" },
{ argumentIndex: 1, parameter: "mode" },
]);
expect(ir.callReturnFlows).toEqual([
expect.objectContaining({
callSiteId: call.callSiteId,
callableId: render.callableId,
returnSiteId: render.returnSites[0]?.returnSiteId,
}),
]);
expect(ir.closureCaptures).toEqual([
expect.objectContaining({
callableId: render.callableId,
bindingId: topLevelBinding(ir, "prefix").bindingId,
}),
]);
expect(ir.frontiers).toEqual([]);
});
it("recovers explicit Promise ownership, chains, aggregation, and awaits", () => {
const ir = analyzeJavaScriptSemantics(`
async function run(value) {
const base = Promise.resolve(value);
const chained = base.then(work).finally(cleanup);
await chained;
Promise.resolve(value).then(work);
return Promise.all([base, Promise.resolve(value)]);
}
const settled = Promise.allSettled([Promise.resolve(1)]);
`);
expect(
ir.promiseOperations.map(
({ kind, method, ownership, sourceResolution }) => ({
kind,
method,
ownership,
sourceResolution,
}),
),
).toEqual(
expect.arrayContaining([
{
kind: "static",
method: "resolve",
ownership: "assigned",
sourceResolution: "complete",
},
{
kind: "chain",
method: "then",
ownership: "chained",
sourceResolution: "complete",
},
{
kind: "chain",
method: "finally",
ownership: "assigned",
sourceResolution: "complete",
},
{
kind: "awaited-expression",
method: "await",
ownership: "awaited",
sourceResolution: "complete",
},
{
kind: "chain",
method: "then",
ownership: "detached",
sourceResolution: "complete",
},
{
kind: "aggregate",
method: "all",
ownership: "returned",
sourceResolution: "complete",
},
{
kind: "aggregate",
method: "allSettled",
ownership: "assigned",
sourceResolution: "complete",
},
]),
);
const aggregate = ir.promiseOperations.find(
({ method }) => method === "all",
);
expect(aggregate?.sourcePromiseIds).toHaveLength(2);
expect(aggregate?.returnSiteId).not.toBeNull();
});
});
describe("JavaScript semantic analysis: calls 2", () => {
it("does not treat a shadowed Promise binding as the intrinsic", () => {
const ir = analyzeJavaScriptSemantics(`
function run(Promise) {
return Promise.resolve(1).then(work);
}
`);
expect(ir.promiseOperations).toEqual([
expect.objectContaining({
kind: "chain",
method: "then",
ownership: "returned",
sourcePromiseIds: [],
sourceResolution: "unresolved",
}),
]);
});
it("bounds Promise recovery with an explicit frontier", () => {
const ir = analyzeJavaScriptSemantics(
`
Promise.resolve(1);
Promise.resolve(2);
Promise.resolve(3);
`,
{ maxPromiseOperations: 1 },
);
expect(ir.promiseOperations).toHaveLength(1);
expect(ir.coverage).toMatchObject({
status: "truncated",
limitsReached: ["maxPromiseOperations"],
});
});
it("fingerprints formatting and local-name changes identically", () => {
const left = analyzeJavaScriptSemantics(`
function calculate(value) {
const result = value + 1;
return result;
}
`);
const right = analyzeJavaScriptSemantics(
"function renamed(input){const output=input+1;return output}",
);
const changed = analyzeJavaScriptSemantics(
"function renamed(input){const output=input+2;return output}",
);
expect(left.functionFingerprints).toHaveLength(1);
expect(right.functionFingerprints).toHaveLength(1);
expect(left.functionFingerprints[0]?.components).toEqual(
right.functionFingerprints[0]?.components,
);
expect(
changed.functionFingerprints[0]?.components.literalSetSha256,
).not.toBe(left.functionFingerprints[0]?.components.literalSetSha256);
});
it("retains ambiguous local callees and explicit dynamic frontiers", () => {
const ir = analyzeJavaScriptSemantics(`
function left(value) { return value; }
function right(value) { return value; }
const selected = chooseLeft ? left : right;
selected(input);
receiver[key](input);
external(input);
`);
const selected = ir.callSites.find(
({ resolution }) => resolution === "ambiguous",
);
expect(selected?.calleeCallableIds).toEqual(
[
onlyCallable(ir, "left").callableId,
onlyCallable(ir, "right").callableId,
].sort(),
);
expect(
ir.argumentFlows.filter(
({ callSiteId }) => callSiteId === selected?.callSiteId,
),
).toHaveLength(2);
expect(ir.frontiers).toEqual(
expect.arrayContaining([
expect.objectContaining({
kind: "dynamic-call",
reason: expect.stringMatching(/ambiguous/iu),
}),
expect.objectContaining({
kind: "dynamic-property",
reason: expect.stringMatching(/computed member/iu),
}),
expect.objectContaining({
kind: "dynamic-call",
reason: "Unresolved call target external.",
}),
]),
);
});
});
@@ -0,0 +1,264 @@
import { it } from "@fast-check/vitest";
import { describe, expect } from "vitest";
import { analyzeJavaScriptSemantics } from "../../../src/domain/javascriptSemanticAnalysis.js";
import {
onlyCallable,
topLevelBinding,
} from "./javascriptSemanticAnalysis.support.js";
describe("JavaScript semantic analysis: dataflow 1", () => {
it("recovers static object reads, writes, spreads, and destructuring", () => {
const ir = analyzeJavaScriptSemantics(`
const source = { token: "TOKEN", count: 1 };
const { token } = source;
const copy = { ...source };
source.count = 2;
const read = source.token;
`);
expect(
ir.objectOperations.map(({ kind, propertyName, resolution }) => ({
kind,
propertyName,
resolution,
})),
).toEqual(
expect.arrayContaining([
{
kind: "destructure",
propertyName: "token",
resolution: "complete",
},
{ kind: "spread", propertyName: null, resolution: "complete" },
{ kind: "write", propertyName: "count", resolution: "complete" },
{ kind: "read", propertyName: "token", resolution: "complete" },
]),
);
});
it("does not project positional argument flow after a spread", () => {
const ir = analyzeJavaScriptSemantics(`
function target(first, second, third) { return third; }
target(one, ...rest, three);
`);
expect(ir.argumentFlows.map(({ argumentIndex }) => argumentIndex)).toEqual([
0,
]);
});
it("applies independent hard bounds to every new semantic fact family", () => {
const ir = analyzeJavaScriptSemantics(
`
const captured = 1;
function target(value, other) { return value + other + captured; }
target(1, 2);
target(3, 4);
object[first];
object[second];
`,
{
maxCallSites: 1,
maxCallArguments: 1,
maxArgumentFlows: 0,
maxCallReturnFlows: 0,
maxClosureCaptures: 0,
maxFrontiers: 1,
},
);
expect(ir.callSites).toHaveLength(1);
expect(ir.callSites[0]?.arguments).toEqual([
expect.objectContaining({ index: 0, spread: false }),
]);
expect(ir.argumentFlows).toEqual([]);
expect(ir.callReturnFlows).toEqual([]);
expect(ir.closureCaptures).toEqual([]);
expect(ir.frontiers).toHaveLength(1);
expect(ir.coverage).toMatchObject({
status: "truncated",
limitsReached: expect.arrayContaining([
"maxCallSites",
"maxCallArguments",
"maxArgumentFlows",
"maxCallReturnFlows",
"maxClosureCaptures",
"maxFrontiers",
]),
});
});
it("recovers only direct return sites with literal and unknown object fields", () => {
const ir = analyzeJavaScriptSemantics(`
export default function parseMarkdown(value) {
if (value.startsWith("# "))
return { type: "heading", depth: 1, text: value.slice(2) };
function nested() { return { type: "nested" }; }
const arrow = () => ({ type: "arrow" });
void nested; void arrow;
return { type: "paragraph", text: value.replaceAll("x", "y") };
}
`);
const parse = onlyCallable(ir, "parseMarkdown");
expect(parse.returnCoverage).toEqual({
status: "complete",
retainedCount: 2,
omittedCount: 0,
limitsReached: [],
});
expect(parse.returnSites).toHaveLength(2);
expect(parse.returnSites[0]?.value).toMatchObject({
status: "object",
unknownProperties: false,
omittedProperties: 0,
properties: expect.arrayContaining([
{ name: "depth", value: { status: "literal", value: 1 } },
{ name: "type", value: { status: "literal", value: "heading" } },
{
name: "text",
value: {
status: "unknown",
reason: "Unsupported CallExpression value.",
},
},
]),
});
expect(onlyCallable(ir, "nested").returnSites).toHaveLength(1);
expect(onlyCallable(ir, "arrow").returnSites).toHaveLength(1);
expect(ir.moduleLinks).toContainEqual(
expect.objectContaining({
exportedName: "default",
callableId: parse.callableId,
}),
);
});
});
describe("JavaScript semantic analysis: dataflow 2", () => {
it("retains partial property coverage, empty returns, and return limits", () => {
const partial = analyzeJavaScriptSemantics(`
const spread = () => ({ type: "spread", ...dynamic });
const computed = () => ({ type: "computed", [key]: 1 });
function noReturn() { throw new Error("stop"); }
function emptyReturn() { return; }
`);
expect(onlyCallable(partial, "spread").returnSites[0]?.value).toMatchObject(
{
status: "object",
unknownProperties: true,
omittedProperties: null,
},
);
expect(
onlyCallable(partial, "computed").returnSites[0]?.value,
).toMatchObject({
status: "object",
unknownProperties: true,
omittedProperties: 1,
});
expect(onlyCallable(partial, "noReturn").returnSites).toEqual([]);
expect(onlyCallable(partial, "emptyReturn").returnSites[0]?.value).toEqual({
status: "unknown",
reason: "Return has no value.",
});
const limited = analyzeJavaScriptSemantics(
"function many(value) { if (value) return 1; return 2; }",
{ maxReturnSites: 1 },
);
expect(onlyCallable(limited, "many")).toMatchObject({
returnSites: [{ value: { status: "literal", value: 1 } }],
returnCoverage: {
status: "truncated",
retainedCount: 1,
omittedCount: 1,
limitsReached: ["maxReturnSites"],
},
});
expect(limited.coverage.limitsReached).toContain("maxReturnSites");
});
it("fails closed on assignment ambiguity, alias cycles, and lattice limits", () => {
const ambiguous = analyzeJavaScriptSemantics(`
let current = "first";
current = "second";
const left = right;
const right = left;
`);
expect(topLevelBinding(ambiguous, "current").value).toMatchObject({
status: "ambiguous",
});
expect(topLevelBinding(ambiguous, "left").value).toMatchObject({
status: "cycle",
});
expect(topLevelBinding(ambiguous, "right").provenance).toMatchObject({
status: "cycle",
});
const limited = analyzeJavaScriptSemantics(
'const channel = enabled ? "one" : "two";',
{ maxUnionValues: 1 },
);
expect(topLevelBinding(limited, "channel").value).toEqual({
status: "limit-reached",
reason: "maxUnionValues reached.",
});
expect(limited.coverage).toMatchObject({
status: "truncated",
limitsReached: ["maxUnionValues"],
});
expect(limited.coverage.omittedCount).toBeGreaterThan(0);
});
it("does not invent exact module paths for dynamic property access", () => {
const ir = analyzeJavaScriptSemantics(`
const key = getKey();
const dynamicMember = require("electron")[key];
const { [key]: dynamicBinding } = require("electron");
`);
expect(topLevelBinding(ir, "dynamicMember").provenance).toMatchObject({
status: "unknown",
origins: [],
});
expect(topLevelBinding(ir, "dynamicBinding").provenance).toMatchObject({
status: "unknown",
origins: [],
});
expect(
ir.moduleLinks.filter(({ localName }) =>
["dynamicMember", "dynamicBinding"].includes(localName ?? ""),
),
).toEqual([]);
});
it("bounds retained scopes and bindings without corrupting outer resolution", () => {
const ir = analyzeJavaScriptSemantics(
`
const retained = "yes";
const omitted = "no";
retained;
function nested(value) { return retained + value; }
`,
{ maxBindings: 1, maxCallables: 0, maxScopes: 1 },
);
expect(ir.bindings.map(({ name }) => name)).toEqual(["retained"]);
expect(ir.callables).toEqual([]);
expect(ir.coverage.status).toBe("truncated");
expect(ir.coverage.limitsReached).toEqual(
expect.arrayContaining(["maxBindings", "maxCallables", "maxScopes"]),
);
expect(ir.references.filter(({ name }) => name === "retained")).toEqual(
expect.arrayContaining([
expect.objectContaining({
resolution: "resolved",
bindingId: topLevelBinding(ir, "retained").bindingId,
}),
expect.objectContaining({ resolution: "unknown", bindingId: null }),
]),
);
});
});
@@ -0,0 +1,173 @@
import { it } from "@fast-check/vitest";
import { describe, expect } from "vitest";
import { analyzeJavaScriptSemantics } from "../../../src/domain/javascriptSemanticAnalysis.js";
describe("JavaScript semantic analysis: native bindings 1", () => {
it("recovers child-process argv, env, stdio, listeners, and signals", () => {
const ir = analyzeJavaScriptSemantics(`
import { spawn as launch } from "node:child_process";
function run() {
const child = launch(
"/bin/tool",
["--mode", "fast"],
{ env: { MODE: "test" }, stdio: ["ignore", "pipe", "pipe"] },
);
child.on("exit", onExit);
child.once("error", onError);
child.kill("SIGINT");
}
`);
expect(ir.childProcessSpawns).toEqual([
expect.objectContaining({
method: "spawn",
command: "/bin/tool",
argvCount: 2,
environmentSupplied: true,
stdioMode: "array",
resolution: "complete",
}),
]);
expect(
ir.childProcessInteractions.map(
({ kind, eventName, signalName, resolution }) => ({
kind,
eventName,
signalName,
resolution,
}),
),
).toEqual([
{
kind: "listener",
eventName: "exit",
signalName: null,
resolution: "complete",
},
{
kind: "listener",
eventName: "error",
signalName: null,
resolution: "complete",
},
{
kind: "signal",
eventName: null,
signalName: "SIGINT",
resolution: "complete",
},
]);
expect(ir.functionFingerprints[0]?.components.effects).toContain(
"child-process",
);
});
it("recovers configuration, requests, response consumers, and boundaries", () => {
const ir = analyzeJavaScriptSemantics(`
import { readFileSync } from "node:fs";
import * as http from "node:http";
async function run(schema) {
const endpoint = process.env.API_URL ?? "https://fallback.test";
const mode = process.argv[2];
const raw = readFileSync("./config.json", "utf8");
const parsed = JSON.parse(raw);
const port = Number(process.env.PORT);
const validated = schema.parse(parsed);
const response = await fetch(endpoint, {
method: "POST",
body: validated,
});
const body = await response.json();
http.request("https://audit.test", { body });
return { mode, port, body };
}
`);
expect(
ir.configurationOperations.map(({ kind, key }) => ({ kind, key })),
).toEqual(
expect.arrayContaining([
{ kind: "environment", key: "API_URL" },
{ kind: "default", key: "API_URL" },
{ kind: "argv", key: "2" },
{ kind: "file", key: "./config.json" },
{ kind: "environment", key: "PORT" },
]),
);
expect(
ir.requestOperations.map(({ kind, method, endpoint, resolution }) => ({
kind,
method,
endpoint,
resolution,
})),
).toEqual(
expect.arrayContaining([
{
kind: "request",
method: "fetch",
endpoint: null,
resolution: "partial",
},
{
kind: "response-consumer",
method: "json",
endpoint: null,
resolution: "complete",
},
{
kind: "request",
method: "request",
endpoint: "https://audit.test",
resolution: "complete",
},
]),
);
expect(
ir.boundaryOperations.map(({ kind, method, resolution }) => ({
kind,
method,
resolution,
})),
).toEqual(
expect.arrayContaining([
{ kind: "parse", method: "JSON.parse", resolution: "complete" },
{ kind: "coerce", method: "Number", resolution: "complete" },
{ kind: "parse", method: "parse", resolution: "partial" },
]),
);
expect(ir.functionFingerprints[0]?.components.effects).toContain("network");
});
});
describe("JavaScript semantic analysis: native bindings 2", () => {
it("recovers built-in resource acquisition and exact local release", () => {
const ir = analyzeJavaScriptSemantics(`
import { open } from "node:fs/promises";
import { connect as dial } from "node:net";
async function run(path) {
const file = await open(path);
const socket = dial({ port: 9000 });
await file.close();
socket.destroy();
}
`);
expect(
ir.resourceOperations.map(({ kind, method, resolution }) => ({
kind,
method,
resolution,
})),
).toEqual([
{ kind: "acquire", method: "open", resolution: "complete" },
{ kind: "acquire", method: "connect", resolution: "complete" },
{ kind: "release", method: "close", resolution: "complete" },
{ kind: "release", method: "destroy", resolution: "complete" },
]);
expect(ir.functionFingerprints[0]?.components.effects).toContain(
"resource",
);
});
});
@@ -0,0 +1,128 @@
import { fc, it } from "@fast-check/vitest";
import { describe, expect } from "vitest";
import { analyzeJavaScriptSemantics } from "../../../src/domain/javascriptSemanticAnalysis.js";
import {
onlyCallable,
topLevelBinding,
} from "./javascriptSemanticAnalysis.support.js";
describe("JavaScript semantic analysis: rejection 1", () => {
it("reports reference, module-link, depth, and object-property limits", () => {
const retained = analyzeJavaScriptSemantics(
`
const first = require("first");
const second = require("second");
first;
second;
`,
{ maxModuleLinks: 1, maxReferences: 1 },
);
expect(retained.moduleLinks).toHaveLength(1);
expect(retained.references).toHaveLength(1);
expect(retained.coverage.limitsReached).toEqual(
expect.arrayContaining(["maxModuleLinks", "maxReferences"]),
);
const object = analyzeJavaScriptSemantics(
"const object = { first: 1, second: 2 };",
{ maxObjectProperties: 1 },
);
expect(topLevelBinding(object, "object").value).toMatchObject({
status: "object",
unknownProperties: true,
});
expect(object.coverage.limitsReached).toContain("maxObjectProperties");
const depth = analyzeJavaScriptSemantics(
'const first = "value"; const second = first;',
{ maxValueDepth: 1 },
);
expect(topLevelBinding(depth, "second").value).toMatchObject({
status: "limit-reached",
});
expect(depth.coverage.limitsReached).toContain("maxValueDepth");
});
it("is deterministic and returns failed coverage for an unparseable source", () => {
const source = 'const { value: renamed } = require("fixture");';
expect(analyzeJavaScriptSemantics(source)).toEqual(
analyzeJavaScriptSemantics(source),
);
expect(analyzeJavaScriptSemantics("function {")).toMatchObject({
scopes: [],
bindings: [],
callables: [],
references: [],
coverage: { status: "failed", omittedCount: null },
});
});
it("does not mark parser-recovered duplicate bindings complete", () => {
const ir = analyzeJavaScriptSemantics(
"const duplicate = 'first'; const duplicate = 'second';",
);
expect(ir.coverage).toMatchObject({
status: "partial",
omittedCount: 0,
});
expect(topLevelBinding(ir, "duplicate").value).toMatchObject({
status: "ambiguous",
});
expect(ir.limitations.join(" ")).toMatch(/parser recovered/iu);
});
it("keeps parser-recovered return shapes partial", () => {
const ir = analyzeJavaScriptSemantics(
`
export default function recovered(value) {
const duplicate = 1;
const duplicate = 2;
return { type: "item", text: render(value) };
}
`,
);
const recovered = onlyCallable(ir, "recovered");
expect(ir.coverage.status).toBe("partial");
expect(recovered.returnCoverage).toMatchObject({
status: "partial",
retainedCount: 1,
omittedCount: 0,
});
expect(recovered.returnSites[0]?.value).toMatchObject({
status: "object",
properties: expect.arrayContaining([
{ name: "type", value: { status: "literal", value: "item" } },
expect.objectContaining({
name: "text",
value: expect.objectContaining({ status: "unknown" }),
}),
]),
});
});
it.prop([fc.string({ maxLength: 512 })])(
"fails closed for arbitrary bounded source text",
(source) => {
const ir = analyzeJavaScriptSemantics(source, {
maxBindings: 64,
maxCallables: 64,
maxModuleLinks: 64,
maxReferences: 256,
maxScopes: 64,
});
expect(ir.schema).toBe("JavaScriptSemanticIR");
expect(["complete", "partial", "truncated", "failed"]).toContain(
ir.coverage.status,
);
if (ir.coverage.status === "failed") {
expect(ir.scopes).toEqual([]);
expect(ir.bindings).toEqual([]);
expect(ir.callables).toEqual([]);
}
},
);
});
@@ -0,0 +1,129 @@
import { it } from "@fast-check/vitest";
import { describe, expect } from "vitest";
import { analyzeJavaScriptSemantics } from "../../../src/domain/javascriptSemanticAnalysis.js";
describe("JavaScript semantic analysis: runtime boundaries 1", () => {
it("recovers EventEmitter candidates and imported timer handle cancellation", () => {
const ir = analyzeJavaScriptSemantics(`
import {
setTimeout as later,
clearTimeout as cancel,
} from "node:timers";
function run(bus, dynamicName) {
const handle = later(work, 25);
bus.on("ready", handler);
bus.once(dynamicName, handler);
bus.emit("ready");
bus.off("ready", handler);
cancel(handle);
}
`);
expect(
ir.eventOperations.map(({ kind, method, eventName, resolution }) => ({
kind,
method,
eventName,
resolution,
})),
).toEqual([
{
kind: "register",
method: "on",
eventName: "ready",
resolution: "complete",
},
{
kind: "register",
method: "once",
eventName: null,
resolution: "unresolved",
},
{
kind: "dispatch",
method: "emit",
eventName: "ready",
resolution: "complete",
},
{
kind: "remove",
method: "off",
eventName: "ready",
resolution: "complete",
},
]);
expect(ir.timerOperations).toEqual([
expect.objectContaining({
kind: "schedule",
method: "setTimeout",
delayMilliseconds: 25,
resolution: "complete",
}),
expect.objectContaining({
kind: "cancel",
method: "clearTimeout",
delayMilliseconds: null,
resolution: "complete",
linkedTimerId: ir.timerOperations[0]?.timerId,
}),
]);
expect(ir.functionFingerprints[0]?.components.effects).toEqual([
"event",
"timer",
]);
});
it("does not treat shadowed timer globals as Node timers", () => {
const ir = analyzeJavaScriptSemantics(`
function run(setTimeout, clearTimeout) {
const handle = setTimeout(work, 1);
clearTimeout(handle);
}
`);
expect(ir.timerOperations).toEqual([]);
});
it("bounds every added semantic effect family independently", () => {
const ir = analyzeJavaScriptSemantics(
`
import { spawn } from "node:child_process";
import { open } from "node:fs/promises";
Promise.resolve(1);
bus.on("ready", handler);
setTimeout(work, 1);
spawn("/bin/tool");
const endpoint = process.env.API_URL;
fetch("https://example.test");
JSON.parse(raw);
open(path);
`,
{
maxPromiseOperations: 0,
maxEventOperations: 0,
maxTimerOperations: 0,
maxChildProcessOperations: 0,
maxConfigurationOperations: 0,
maxRequestOperations: 0,
maxBoundaryOperations: 0,
maxResourceOperations: 0,
maxObjectOperations: 0,
},
);
expect(ir.coverage.limitsReached).toEqual(
expect.arrayContaining([
"maxBoundaryOperations",
"maxChildProcessOperations",
"maxConfigurationOperations",
"maxEventOperations",
"maxPromiseOperations",
"maxRequestOperations",
"maxResourceOperations",
"maxTimerOperations",
"maxObjectOperations",
]),
);
});
});
@@ -0,0 +1,209 @@
import { it } from "@fast-check/vitest";
import { describe, expect } from "vitest";
import { analyzeJavaScriptSemantics } from "../../../src/domain/javascriptSemanticAnalysis.js";
import {
semanticBinding,
semanticReferenceAt,
} from "../../../src/domain/javascriptSemanticIr.js";
import {
programScope,
bindingsNamed,
onlyBinding,
topLevelBinding,
origin,
} from "./javascriptSemanticAnalysis.support.js";
describe("JavaScript semantic analysis: structure 1", () => {
it("resolves imports, require destructuring, aliases, assignments, and shadowing", () => {
const ir = analyzeJavaScriptSemantics(`
import { ipcRenderer as ir } from "electron";
const { ipcMain: bus } = require("electron");
const forwarded = bus;
let assigned;
assigned = ir;
ir.invoke("outside");
bus.handle("main", handler);
function local(ipcRenderer) {
const bus = require("./local-bus.js");
ipcRenderer.send("shadowed");
return bus;
}
`);
expect(ir.coverage).toEqual({
status: "complete",
omittedCount: 0,
limitsReached: [],
});
expect(origin(topLevelBinding(ir, "ir"))).toEqual({
specifier: "electron",
importedPath: ["ipcRenderer"],
});
expect(origin(topLevelBinding(ir, "bus"))).toEqual({
specifier: "electron",
importedPath: ["ipcMain"],
});
expect(origin(topLevelBinding(ir, "forwarded"))).toEqual({
specifier: "electron",
importedPath: ["ipcMain"],
});
expect(origin(topLevelBinding(ir, "assigned"))).toEqual({
specifier: "electron",
importedPath: ["ipcRenderer"],
});
expect(ir.moduleLinks).toEqual(
expect.arrayContaining([
expect.objectContaining({
kind: "require",
specifier: "electron",
importedName: "ipcMain",
localName: "bus",
}),
]),
);
const innerBus = bindingsNamed(ir, "bus").find(
({ scopeId }) => scopeId !== programScope(ir).scopeId,
);
expect(innerBus).toBeDefined();
if (innerBus === undefined) return;
expect(origin(innerBus)).toEqual({
specifier: "./local-bus.js",
importedPath: [],
});
const shadow = onlyBinding(ir, "ipcRenderer");
expect(shadow.provenance).toEqual({
status: "local",
origins: [],
reason: null,
});
const shadowReference = ir.references.find(
({ name, bindingId, role }) =>
name === "ipcRenderer" &&
bindingId === shadow.bindingId &&
role === "read",
);
expect(shadowReference?.resolution).toBe("resolved");
expect(shadowReference?.bindingId).not.toBe(
topLevelBinding(ir, "ir").bindingId,
);
if (shadowReference === undefined || shadowReference.bindingId === null)
throw new Error("Missing shadow reference");
expect(semanticBinding(ir, shadowReference.bindingId)).toEqual(shadow);
expect(
semanticReferenceAt(
ir,
shadowReference.location.start.line,
shadowReference.location.start.column,
),
).toEqual(shadowReference);
});
it("propagates literal, template, object, conditional, and destructured values", () => {
const ir = analyzeJavaScriptSemantics(`
const prefix = "rea";
const suffix = "open";
const channel = \`${"${prefix}"}:${"${suffix}"}\`;
const options = {
channel,
mode: enabled ? "read" : "write",
};
const selected = options.channel;
const { mode } = options;
const [first] = ["zero", "one"];
`);
expect(topLevelBinding(ir, "channel").value).toEqual({
status: "literal",
value: "rea:open",
});
expect(topLevelBinding(ir, "selected").value).toEqual({
status: "literal",
value: "rea:open",
});
expect(topLevelBinding(ir, "mode").value).toEqual({
status: "union",
values: ["read", "write"],
});
expect(topLevelBinding(ir, "first").value).toEqual({
status: "literal",
value: "zero",
});
});
});
describe("JavaScript semantic analysis: structure 2", () => {
it("retains ESM, re-export, require, and CommonJS export relationships", () => {
const ir = analyzeJavaScriptSemantics(`
export { ipcRenderer as bridge } from "electron";
export * from "./wrapper.js";
export const localValue = 1;
const addon = require("./native.node");
module.exports.addon = addon;
export default function namedDefault() {}
`);
expect(ir.moduleLinks).toEqual(
expect.arrayContaining([
expect.objectContaining({
kind: "re-export",
specifier: "electron",
importedName: "ipcRenderer",
exportedName: "bridge",
}),
expect.objectContaining({
kind: "re-export",
specifier: "./wrapper.js",
importedName: "*",
exportedName: "*",
}),
expect.objectContaining({
kind: "export",
localName: "localValue",
exportedName: "localValue",
}),
expect.objectContaining({
kind: "require",
specifier: "./native.node",
localName: "addon",
}),
expect.objectContaining({
kind: "commonjs-export",
localName: "addon",
exportedName: "addon",
}),
expect.objectContaining({
kind: "export",
localName: "namedDefault",
exportedName: "default",
}),
]),
);
});
it("keeps function, class, and method identities separate from bindings", () => {
const ir = analyzeJavaScriptSemantics(`
class Service {
run() {}
get value() { return 1; }
#privateMethod() {}
}
const arrow = () => 1;
const object = { method() {} };
`);
expect(ir.callables).toEqual(
expect.arrayContaining([
expect.objectContaining({ kind: "class", name: "Service" }),
expect.objectContaining({ kind: "method", name: "run" }),
expect.objectContaining({ kind: "method", name: "value" }),
expect.objectContaining({ kind: "method", name: "#privateMethod" }),
expect.objectContaining({ kind: "function", name: "arrow" }),
expect.objectContaining({ kind: "method", name: "method" }),
]),
);
expect(bindingsNamed(ir, "run")).toEqual([]);
expect(bindingsNamed(ir, "method")).toEqual([]);
});
});
@@ -0,0 +1,61 @@
import { expect } from "vitest";
import type {
JavaScriptSemanticBinding,
JavaScriptSemanticIr,
} from "../../../src/domain/javascriptSemanticIr.js";
export const programScope = (ir: JavaScriptSemanticIr) => {
const scope = ir.scopes.find(({ kind }) => kind === "program");
if (scope === undefined) throw new Error("Missing program scope");
return scope;
};
export const bindingsNamed = (
ir: JavaScriptSemanticIr,
name: string,
): JavaScriptSemanticBinding[] =>
ir.bindings.filter(({ name: candidate }) => candidate === name);
export const onlyBinding = (
ir: JavaScriptSemanticIr,
name: string,
): JavaScriptSemanticBinding => {
const bindings = bindingsNamed(ir, name);
expect(bindings).toHaveLength(1);
const binding = bindings[0];
if (binding === undefined) throw new Error(`Missing binding ${name}`);
return binding;
};
export const onlyCallable = (ir: JavaScriptSemanticIr, name: string) => {
const callables = ir.callables.filter(
({ name: candidate }) => candidate === name,
);
if (callables.length !== 1 || callables[0] === undefined)
throw new Error(`Expected one callable named ${name}`);
return callables[0];
};
export const topLevelBinding = (
ir: JavaScriptSemanticIr,
name: string,
): JavaScriptSemanticBinding => {
const scopeId = programScope(ir).scopeId;
const binding = ir.bindings.find(
({ name: candidate, scopeId: candidateScope }) =>
candidate === name && candidateScope === scopeId,
);
if (binding === undefined)
throw new Error(`Missing top-level binding ${name}`);
return binding;
};
export const origin = (binding: JavaScriptSemanticBinding) => {
expect(binding.provenance.status).toBe("module");
expect(binding.provenance.origins).toHaveLength(1);
const value = binding.provenance.origins[0];
if (value === undefined)
throw new Error(`Missing origin for ${binding.name}`);
return value;
};
@@ -0,0 +1,317 @@
import { expect, it } from "vitest";
import { buildJavaScriptSemanticGraph } from "../../../src/application/JavaScriptSemanticGraphBuilder.js";
import type { JavaScriptArtifactAnalysis } from "../../../src/application/JavaScriptArtifactAnalysisTypes.js";
import type { JavaScriptArtifactFile } from "../../../src/application/JavaScriptArtifactFiles.js";
import { queryJavaScriptSemanticGraph } from "../../../src/domain/javascriptSemanticQuery.js";
import { analyzeJavaScriptSemantics } from "../../../src/domain/javascriptSemanticAnalysis.js";
import {
DEFAULT_JAVASCRIPT_SEMANTIC_LIMITS,
type JavaScriptSemanticLimits,
} from "../../../src/domain/javascriptSemanticIr.js";
const SHA256 = "a".repeat(64);
const GRAPH_ID = `jag_${"b".repeat(64)}`;
it("projects closure and direct interprocedural flow without execution", () => {
const graph = graphFor(`
const outer = 2;
function add(value) { return value + outer; }
const input = 40;
const answer = add(input);
`);
const relations = new Set(graph.relations.map(({ relation }) => relation));
for (const expected of [
"argument-to-parameter",
"calls",
"captures",
"defines",
"reads",
"returns-to-call",
] as const)
expect(relations.has(expected)).toBe(true);
expect(graph.coverage.families).toHaveLength(12);
expect(graph.limitations).toContain(
"The semantic graph contains static syntax observations and conservative relationship candidates; it does not claim runtime execution.",
);
const parameter = graph.nodes.find(
({ kind, label }) => kind === "parameter" && label === "value",
);
if (parameter === undefined) throw new Error("Expected parameter node");
const provenance = queryJavaScriptSemanticGraph(graph, {
seed: { kind: "semantic-node", node_id: parameter.node_id },
direction: "backward-provenance",
include_ambiguous_dynamic_edges: true,
});
expect(provenance.relations.map(({ relation }) => relation)).toEqual(
expect.arrayContaining([
"aliases",
"argument-to-parameter",
"defines",
"reads",
]),
);
});
it("keeps dynamic calls explicit and returns bounded deterministic pages", () => {
const graph = graphFor(`
const handlers = { ready() { return 1; } };
const key = process.argv[2];
handlers[key]();
`);
expect(graph.unknowns.some(({ reason }) => reason === "dynamic-call")).toBe(
true,
);
const seedNodeId = graph.relations.find(
({ relation }) => relation === "defines",
)?.source_node_id;
expect(seedNodeId).toBeDefined();
if (seedNodeId === undefined) throw new Error("Expected a definition seed");
const first = queryJavaScriptSemanticGraph(graph, {
seed: { kind: "semantic-node", node_id: seedNodeId },
direction: "forward-influence",
include_ambiguous_dynamic_edges: true,
limits: {
max_seed_matches: 25,
max_nodes: 2_000,
max_edges: 4_000,
max_depth: 12,
max_functions: 500,
max_modules: 500,
page_size: 1,
},
});
const repeated = queryJavaScriptSemanticGraph(graph, {
seed: { kind: "semantic-node", node_id: seedNodeId },
direction: "forward-influence",
include_ambiguous_dynamic_edges: true,
limits: first.applied_limits,
});
expect(repeated).toEqual(first);
});
it("keeps ambiguous interprocedural flow out of the default traversal", () => {
const graph = graphFor(`
function left(value) { return value; }
function right(value) { return value; }
const input = 1;
const selected = Math.random() ? left : right;
selected(input);
`);
const input = graph.nodes.find(
({ kind, label }) => kind === "binding" && label === "input",
);
if (input === undefined) throw new Error("Expected input binding");
const query = {
seed: { kind: "semantic-node" as const, node_id: input.node_id },
direction: "forward-influence" as const,
allowed_relations: [
"reads" as const,
"aliases" as const,
"argument-to-parameter" as const,
],
};
const strict = queryJavaScriptSemanticGraph(graph, query);
expect(
strict.relations.some(
({ relation }) => relation === "argument-to-parameter",
),
).toBe(false);
expect(strict.status).toBe("ambiguous");
const admitted = queryJavaScriptSemanticGraph(graph, {
...query,
include_ambiguous_dynamic_edges: true,
});
expect(
admitted.relations.filter(
({ relation }) => relation === "argument-to-parameter",
),
).toHaveLength(2);
expect(admitted.status).toBe("ambiguous");
});
it("connects caller results, direct returns, parameters, and captures", () => {
const graph = graphFor(`
const outer = 2;
function identity(value) { return value; }
function readOuter() { return outer; }
const input = 40;
const output = identity(input);
`);
const binding = (label: string) =>
graph.nodes.find(
({ kind, label: nodeLabel }) =>
["binding", "parameter"].includes(kind) && nodeLabel === label,
);
const output = binding("output");
const input = binding("input");
const outer = binding("outer");
const readOuter = graph.nodes.find(
({ kind, label }) => kind === "function" && label === "readOuter",
);
if (
output === undefined ||
input === undefined ||
outer === undefined ||
readOuter === undefined
)
throw new Error("Expected semantic flow nodes");
const provenance = queryJavaScriptSemanticGraph(graph, {
seed: { kind: "semantic-node", node_id: output.node_id },
direction: "backward-provenance",
});
expect(provenance.nodes.map(({ node_id }) => node_id)).toContain(
input.node_id,
);
const influence = queryJavaScriptSemanticGraph(graph, {
seed: { kind: "semantic-node", node_id: outer.node_id },
direction: "forward-influence",
allowed_relations: ["captures"],
});
expect(influence.nodes.map(({ node_id }) => node_id)).toContain(
readOuter.node_id,
);
const capture = graph.relations.find(
({ relation }) => relation === "captures",
);
expect(capture?.evidence.location).toMatchObject({
available: true,
value: { kind: "source-range", source: "app.js" },
});
expect(capture?.evidence.location).not.toEqual(readOuter.evidence.location);
});
it("preserves semantic analyzer truncation in graph coverage", () => {
const graph = graphFor(
"const first = 1; const second = first; const third = second;",
{ maxReferences: 1 },
);
expect(graph.coverage).toMatchObject({
status: "partial",
truncated: true,
omitted_nodes: null,
omitted_relations: null,
limits: expect.arrayContaining([
{ name: "semantic.maxReferences", value: 1, unit: "items" },
]),
});
expect(
graph.coverage.families.find(
({ family }) => family === "promise-ownership",
),
).toMatchObject({ status: "unknown", retained_relations: 0 });
});
it("projects bounded Promise ownership and unresolved sources", () => {
const graph = graphFor(`
async function run(value) {
const owned = new Promise((resolve) => resolve(value));
await Promise.resolve(owned);
Promise.resolve(value).then(work).finally(cleanup);
value.then(work);
return Promise.all([owned, Promise.resolve(value)]);
}
`);
const relations = new Set(graph.relations.map(({ relation }) => relation));
for (const expected of [
"aggregates",
"awaits",
"chains",
"creates-promise",
"detaches-task",
"owns",
"returns-task",
] as const)
expect(relations.has(expected)).toBe(true);
expect(graph.nodes.filter(({ kind }) => kind === "promise")).not.toHaveLength(
0,
);
expect(
graph.nodes.find(
({ kind, properties }) =>
kind === "promise" &&
properties.method === "all" &&
properties.ownership === "returned",
),
).toBeDefined();
expect(
graph.unknowns.some(
({ family, reason }) =>
family === "promise-ownership" && reason === "ambiguous-target",
),
).toBe(true);
expect(
graph.coverage.families.find(
({ family }) => family === "promise-ownership",
),
).toMatchObject({ status: "partial" });
});
it("keeps duplicate function fingerprints ambiguous", () => {
const graph = graphFor(`
function first(value) { return value + 1; }
function second(input) { return input + 1; }
`);
expect(graph.fingerprints).toHaveLength(2);
const digest = graph.fingerprints[0]?.fingerprint_sha256;
expect(digest).toBeDefined();
expect(graph.fingerprints[1]?.fingerprint_sha256).toBe(digest);
if (digest === undefined) throw new Error("Expected fingerprint");
const query = queryJavaScriptSemanticGraph(graph, {
seed: { kind: "function", fingerprint_sha256: digest },
direction: "forward-influence",
});
expect(query.status).toBe("ambiguous");
expect(query.summary.total_seed_matches).toBe(2);
});
const graphFor = (
source: string,
inputLimits: Partial<JavaScriptSemanticLimits> = {},
) => {
const file: JavaScriptArtifactFile = {
path: "app.js",
container_sha256: SHA256,
sha256: SHA256,
bytes: Buffer.byteLength(source),
inventory_artifact_id: `art_${SHA256}`,
kind: "javascript",
unpacked: false,
text: { included: true, value: source },
};
const semanticLimits = {
...DEFAULT_JAVASCRIPT_SEMANTIC_LIMITS,
...inputLimits,
};
const analysis: JavaScriptArtifactAnalysis = {
files: [
{
file,
javascript: null,
semantic: {
ir: analyzeJavaScriptSemantics(source, inputLimits),
limits: semanticLimits,
},
},
],
packages: [],
json_modules: [],
html_scripts: [],
source_maps: [],
visited_ast_nodes: 0,
findings: 0,
modules: 0,
parse_failures: 0,
truncated_scopes: 0,
limitations: [],
};
return buildJavaScriptSemanticGraph({
rootArtifactSha256: SHA256,
applicationGraph: { graph_id: GRAPH_ID, nodes: [] },
analysis,
});
};
@@ -0,0 +1,278 @@
import { expect, it } from "vitest";
import type { ApplicationGraphEvidence } from "../../../src/domain/javascriptApplicationEvidenceSchemas.js";
import {
JAVASCRIPT_SEMANTIC_NODE_KINDS,
JAVASCRIPT_SEMANTIC_RELATION_FAMILIES,
JAVASCRIPT_SEMANTIC_RELATIONS,
} from "../../../src/domain/javascriptSemanticGraphSchemas.js";
import {
createJavaScriptSemanticFingerprint,
createJavaScriptSemanticGraph,
createJavaScriptSemanticGraphNode,
createJavaScriptSemanticGraphRelation,
createJavaScriptSemanticGraphUnknown,
type JavaScriptSemanticGraph,
type JavaScriptSemanticGraphNode,
} from "../../../src/domain/javascriptSemanticGraph.js";
import {
parseJavaScriptSemanticGraph,
serializeJavaScriptSemanticGraph,
} from "../../../src/domain/javascriptSemanticGraphSerialization.js";
const SHA = "a".repeat(64);
const JAG_ID = `jag_${"b".repeat(64)}`;
const completeCoverage = {
status: "complete" as const,
truncated: false,
omitted_count: 0,
limits: [],
};
const evidence = (
state: "observed" | "inferred" = "observed",
): ApplicationGraphEvidence => ({
authority:
state === "observed"
? "ast-static-analysis"
: "static-relationship-inference",
state,
confidence: state === "observed" ? "exact" : "high",
artifact: { available: true, artifact_id: `art_${SHA}`, sha256: SHA },
location: {
available: true,
value: {
kind: "source-range",
source: "bundle.js",
start: { line: 1, column: 0 },
end: { line: 1, column: 10 },
},
},
extractor: {
name: "test",
version: "1",
operation: "recover-semantic-relation",
executable_sha256: null,
},
coverage: completeCoverage,
limitations:
state === "observed"
? []
: ["Static reachability does not prove runtime execution."],
evidence_ids: [],
});
const unknownEvidence = (): ApplicationGraphEvidence => ({
authority: "unknown",
state: "unknown",
confidence: "unknown",
artifact: {
available: false,
reason: "unknown",
detail: "Unknown artifact.",
},
location: {
available: false,
reason: "unresolved",
detail: "Dynamic call target.",
},
extractor: {
name: "test",
version: "1",
operation: "retain-dynamic-call",
executable_sha256: null,
},
coverage: {
status: "unknown",
truncated: false,
omitted_count: null,
limits: [],
},
limitations: ["Dynamic call target remains unknown."],
evidence_ids: [],
});
const node = (
kind: (typeof JAVASCRIPT_SEMANTIC_NODE_KINDS)[number],
role: string,
properties: Record<string, string | number | boolean | null> = {},
functionNodeId: string | null = null,
): JavaScriptSemanticGraphNode =>
createJavaScriptSemanticGraphNode({
kind,
identity: {
artifact_sha256: SHA,
module_path: "bundle.js",
source_range: {
start: { line: 1, column: role.length },
end: { line: 1, column: role.length + 1 },
},
role_key: role,
},
function_node_id: functionNodeId,
application_node_ids: [],
label: role,
properties,
evidence: evidence(),
});
const fixtureGraph = (withUnknown = false): JavaScriptSemanticGraph => {
const module = node("module", "module");
const literal = node("literal", "literal", { value: "TOKEN" });
const binding = node("binding", "binding");
const callable = node("function", "function");
const request = node("request", "request", {
endpoint: "https://example.invalid/v1",
});
const relations = [
createJavaScriptSemanticGraphRelation({
source_node_id: literal.node_id,
target_node_id: binding.node_id,
relation: "defines",
resolution: "resolved",
properties: {},
evidence: evidence("inferred"),
}),
createJavaScriptSemanticGraphRelation({
source_node_id: binding.node_id,
target_node_id: callable.node_id,
relation: "captures",
resolution: "resolved",
properties: {},
evidence: evidence("inferred"),
}),
createJavaScriptSemanticGraphRelation({
source_node_id: callable.node_id,
target_node_id: request.node_id,
relation: "constructs-request",
resolution: "resolved",
properties: {},
evidence: evidence("inferred"),
}),
];
const dynamic = createJavaScriptSemanticGraphUnknown({
node_id: callable.node_id,
family: "call-flow",
relation_kinds: ["calls"],
reason: "dynamic-call",
detail: "Computed callee is unresolved.",
candidate_node_ids: [],
evidence: unknownEvidence(),
});
const unknowns = withUnknown ? [dynamic] : [];
const coverageFamilies = JAVASCRIPT_SEMANTIC_RELATION_FAMILIES.map(
(family) => ({
family,
status:
withUnknown && family === "call-flow"
? ("unknown" as const)
: ("complete" as const),
retained_relations: relations.filter(({ relation }) =>
relation === "defines"
? family === "data-flow"
: relation === "captures"
? family === "closure"
: family === "request",
).length,
omitted_relations: withUnknown && family === "call-flow" ? null : 0,
unknown_ids:
withUnknown && family === "call-flow" ? [dynamic.unknown_id] : [],
}),
);
const fingerprint = createJavaScriptSemanticFingerprint({
function_node_id: callable.node_id,
algorithm: "rea.javascript-semantic-function/v1",
status: "complete",
components: {
parameter_arity: 0,
normalized_ast_sha256: "1".repeat(64),
control_flow_sha256: "2".repeat(64),
relation_shape_sha256: "3".repeat(64),
literal_set_sha256: "4".repeat(64),
effects: ["network"],
},
limitations: [],
evidence: evidence("inferred"),
});
return createJavaScriptSemanticGraph({
schema: "JavaScriptSemanticRelationGraph",
schema_version: 1,
root_artifact_sha256: SHA,
application_graph_id: JAG_ID,
root_node_ids: [module.node_id],
nodes: [request, callable, binding, literal, module],
relations,
fingerprints: [fingerprint],
unknowns,
coverage: {
status: withUnknown ? "partial" : "complete",
truncated: false,
omitted_nodes: withUnknown ? null : 0,
omitted_relations: withUnknown ? null : 0,
limits: [],
families: coverageFamilies,
},
limitations: withUnknown ? ["Dynamic call target remains unknown."] : [],
});
};
it("defines every required v1 relation family and canonicalizes records", () => {
expect(JAVASCRIPT_SEMANTIC_RELATIONS).toContain("argument-to-parameter");
expect(JAVASCRIPT_SEMANTIC_RELATIONS).toContain("detaches-task");
expect(JAVASCRIPT_SEMANTIC_RELATIONS).toContain("forwards-signal");
expect(JAVASCRIPT_SEMANTIC_RELATIONS).toContain("validates");
const graph = fixtureGraph();
expect(
parseJavaScriptSemanticGraph(
JSON.parse(serializeJavaScriptSemanticGraph(graph)),
),
).toEqual(graph);
expect(graph.nodes.map(({ node_id }) => node_id)).toEqual(
graph.nodes.map(({ node_id }) => node_id).toSorted(),
);
});
it("rejects stale identities, dangling endpoints, and incomplete coverage claims", () => {
const graph = fixtureGraph();
const { graph_id: _graphId, ...graphInput } = graph;
expect(() =>
parseJavaScriptSemanticGraph({
...graph,
graph_id: `jsrg_${"0".repeat(64)}`,
}),
).toThrow();
expect(() =>
createJavaScriptSemanticGraph({
...graphInput,
relations: [
{
...graph.relations[0],
target_node_id: `jsrg_node_${"f".repeat(64)}`,
},
],
}),
).toThrow();
expect(() =>
createJavaScriptSemanticGraph({
...graphInput,
coverage: { ...graph.coverage, omitted_nodes: 1 },
}),
).toThrow(/Complete graph coverage/u);
const graphWithUnknown = fixtureGraph(true);
const { graph_id: _unknownGraphId, ...unknownGraphInput } = graphWithUnknown;
const originalUnknown = graphWithUnknown.unknowns[0];
if (originalUnknown === undefined)
throw new Error("Expected unknown frontier");
const { unknown_id: _unknownId, ...unknownInput } = originalUnknown;
expect(() =>
createJavaScriptSemanticGraph({
...unknownGraphInput,
unknowns: [
createJavaScriptSemanticGraphUnknown({
...unknownInput,
candidate_node_ids: [`jsrg_node_${"f".repeat(64)}`],
}),
],
}),
).toThrow(/candidate node is absent/u);
});
@@ -0,0 +1,318 @@
import { expect, it } from "vitest";
import { buildJavaScriptSemanticGraph } from "../../../src/application/JavaScriptSemanticGraphBuilder.js";
import type { JavaScriptArtifactAnalysis } from "../../../src/application/JavaScriptArtifactAnalysisTypes.js";
import type { JavaScriptArtifactFile } from "../../../src/application/JavaScriptArtifactFiles.js";
import { queryJavaScriptSemanticGraph } from "../../../src/domain/javascriptSemanticQuery.js";
import { analyzeJavaScriptSemantics } from "../../../src/domain/javascriptSemanticAnalysis.js";
import {
DEFAULT_JAVASCRIPT_SEMANTIC_LIMITS,
type JavaScriptSemanticLimits,
} from "../../../src/domain/javascriptSemanticIr.js";
const SHA256 = "a".repeat(64);
const GRAPH_ID = `jag_${"b".repeat(64)}`;
it("projects literal events and exact timer cancellation", () => {
const graph = graphFor(`
function run(bus, dynamicName) {
const handle = setInterval(tick, 10);
bus.on("ready", handler);
bus.once(dynamicName, handler);
bus.emit("ready");
bus.removeListener("ready", handler);
clearInterval(handle);
}
`);
const relations = new Set(graph.relations.map(({ relation }) => relation));
for (const expected of [
"cancels-timer",
"dispatches-candidate",
"registers-listener",
"removes-listener",
"schedules-timer",
] as const)
expect(relations.has(expected)).toBe(true);
expect(
graph.nodes.find(
({ kind, properties }) =>
kind === "event" && properties.event_name === "ready",
),
).toBeDefined();
expect(
graph.unknowns.some(
({ family, detail }) =>
family === "event" && detail.includes("Dynamic once event name"),
),
).toBe(true);
expect(
graph.coverage.families.find(({ family }) => family === "event"),
).toMatchObject({ status: "partial" });
expect(
graph.coverage.families.find(({ family }) => family === "timer"),
).toMatchObject({ status: "partial" });
});
it("projects child-process creation, I/O, listeners, and signals", () => {
const graph = graphFor(`
import { spawn } from "node:child_process";
function run(command) {
const child = spawn(
command,
["--mode", "fast"],
{ env: process.env, stdio: "pipe" },
);
child.on("exit", onExit);
child.once("error", onError);
child.kill("SIGTERM");
}
`);
const relations = new Set(graph.relations.map(({ relation }) => relation));
for (const expected of [
"connects-stdio",
"forwards-signal",
"listens-error",
"listens-exit",
"spawns",
"supplies-argv",
"supplies-env",
] as const)
expect(relations.has(expected)).toBe(true);
expect(
graph.nodes.find(
({ kind, properties }) =>
kind === "child-process" &&
properties.method === "spawn" &&
properties.command === null,
),
).toBeDefined();
expect(
graph.unknowns.some(
({ family, detail }) =>
family === "child-process" &&
detail.includes("command remains unresolved"),
),
).toBe(true);
expect(
graph.coverage.families.find(({ family }) => family === "child-process"),
).toMatchObject({ status: "partial" });
});
it("projects config precedence, request fields, and boundaries", () => {
const graph = graphFor(`
import { readFileSync } from "node:fs";
async function run(schema) {
const endpoint = process.env.API_URL ?? "https://fallback.test";
const raw = readFileSync("./config.json", "utf8");
const parsed = JSON.parse(raw);
const port = Number(process.argv[2]);
const validated = schema.parse(parsed);
const response = await fetch(endpoint, {
method: "POST",
body: validated,
});
return response.json();
}
`);
const relations = new Set(graph.relations.map(({ relation }) => relation));
for (const expected of [
"coerces",
"constructs-request",
"consumed-by",
"defaults",
"overrides",
"parses",
"reads-argv",
"reads-config",
"reads-environment",
"supplies-request-field",
] as const)
expect(relations.has(expected)).toBe(true);
expect(
graph.nodes.find(
({ kind, properties }) =>
kind === "request" && properties.method === "fetch",
),
).toBeDefined();
expect(
graph.nodes.filter(({ kind }) => kind === "boundary"),
).not.toHaveLength(0);
expect(
graph.coverage.families.find(({ family }) => family === "configuration"),
).toMatchObject({ status: "partial" });
expect(
graph.coverage.families.find(({ family }) => family === "request"),
).toMatchObject({ status: "partial" });
expect(
graph.coverage.families.find(({ family }) => family === "boundary"),
).toMatchObject({ status: "partial" });
});
it("projects built-in resource acquisition and release", () => {
const graph = graphFor(`
import { open } from "node:fs/promises";
import { connect } from "node:net";
async function run(path) {
const file = await open(path);
const socket = connect({ port: 9000 });
await file.close();
socket.end();
}
`);
const relations = new Set(graph.relations.map(({ relation }) => relation));
expect(relations.has("acquires")).toBe(true);
expect(relations.has("releases")).toBe(true);
expect(graph.nodes.filter(({ kind }) => kind === "resource")).toHaveLength(2);
expect(
graph.coverage.families.find(
({ family }) => family === "resource-lifecycle",
),
).toMatchObject({ status: "partial" });
});
it("projects literal seeds and static object flow", () => {
const graph = graphFor(`
const source = { token: "TOKEN", count: 1 };
const { token } = source;
const copy = { ...source };
source.count = 2;
const read = source.token;
`);
const relations = new Set(graph.relations.map(({ relation }) => relation));
for (const expected of [
"destructures",
"reads-property",
"spreads",
"writes-property",
] as const)
expect(relations.has(expected)).toBe(true);
expect(
graph.nodes.find(
({ kind, properties }) =>
kind === "property-slot" && properties.name === "token",
),
).toBeDefined();
const literal = queryJavaScriptSemanticGraph(graph, {
seed: { kind: "literal", value: "TOKEN" },
direction: "forward-influence",
});
expect(literal.status).toBe("ambiguous");
expect(literal.summary.total_seed_matches).toBe(3);
const property = queryJavaScriptSemanticGraph(graph, {
seed: { kind: "property", name: "token" },
direction: "forward-influence",
});
expect(property.status).toBe("found");
});
it("does not promote transformed return expressions to resolved aliases", () => {
const graph = graphFor(`
function increment(value) { return value + 1; }
const input = 1;
const output = increment(input);
`);
const returnNode = graph.nodes.find(({ kind }) => kind === "return-site");
if (returnNode === undefined) throw new Error("Expected return site");
expect(
graph.relations.filter(
({ relation, target_node_id }) =>
relation === "aliases" && target_node_id === returnNode.node_id,
),
).toEqual([expect.objectContaining({ resolution: "candidate" })]);
const output = graph.nodes.find(
({ kind, label }) => kind === "binding" && label === "output",
);
const input = graph.nodes.find(
({ kind, label }) => kind === "binding" && label === "input",
);
if (output === undefined || input === undefined)
throw new Error("Expected caller bindings");
const strict = queryJavaScriptSemanticGraph(graph, {
seed: { kind: "semantic-node", node_id: output.node_id },
direction: "backward-provenance",
});
expect(strict.nodes.map(({ node_id }) => node_id)).not.toContain(
input.node_id,
);
expect(strict.status).toBe("ambiguous");
});
it("uses unavailable evidence when no source produced semantic IR", () => {
const graph = buildJavaScriptSemanticGraph({
rootArtifactSha256: SHA256,
applicationGraph: { graph_id: GRAPH_ID, nodes: [] },
analysis: emptyAnalysis(),
});
expect(graph.nodes).toHaveLength(1);
expect(graph.nodes[0]?.evidence).toMatchObject({
authority: "unknown",
state: "unavailable",
location: { available: false, reason: "not-observed" },
});
});
const emptyAnalysis = (): JavaScriptArtifactAnalysis => ({
files: [],
packages: [],
json_modules: [],
html_scripts: [],
source_maps: [],
visited_ast_nodes: 0,
findings: 0,
modules: 0,
parse_failures: 0,
truncated_scopes: 0,
limitations: [],
});
const graphFor = (
source: string,
inputLimits: Partial<JavaScriptSemanticLimits> = {},
) => {
const file: JavaScriptArtifactFile = {
path: "app.js",
container_sha256: SHA256,
sha256: SHA256,
bytes: Buffer.byteLength(source),
inventory_artifact_id: `art_${SHA256}`,
kind: "javascript",
unpacked: false,
text: { included: true, value: source },
};
const semanticLimits = {
...DEFAULT_JAVASCRIPT_SEMANTIC_LIMITS,
...inputLimits,
};
const analysis: JavaScriptArtifactAnalysis = {
files: [
{
file,
javascript: null,
semantic: {
ir: analyzeJavaScriptSemantics(source, inputLimits),
limits: semanticLimits,
},
},
],
packages: [],
json_modules: [],
html_scripts: [],
source_maps: [],
visited_ast_nodes: 0,
findings: 0,
modules: 0,
parse_failures: 0,
truncated_scopes: 0,
limitations: [],
};
return buildJavaScriptSemanticGraph({
rootArtifactSha256: SHA256,
applicationGraph: { graph_id: GRAPH_ID, nodes: [] },
analysis,
});
};
@@ -0,0 +1,446 @@
import { expect, it } from "vitest";
import type { ApplicationGraphEvidence } from "../../../src/domain/javascriptApplicationEvidenceSchemas.js";
import {
JAVASCRIPT_SEMANTIC_NODE_KINDS,
JAVASCRIPT_SEMANTIC_RELATION_FAMILIES,
} from "../../../src/domain/javascriptSemanticGraphSchemas.js";
import {
createJavaScriptSemanticFingerprint,
createJavaScriptSemanticGraph,
createJavaScriptSemanticGraphNode,
createJavaScriptSemanticGraphRelation,
createJavaScriptSemanticGraphUnknown,
type JavaScriptSemanticGraph,
type JavaScriptSemanticGraphNode,
} from "../../../src/domain/javascriptSemanticGraph.js";
import { queryJavaScriptSemanticGraph } from "../../../src/domain/javascriptSemanticQuery.js";
import { javaScriptSemanticQueryInputSchema } from "../../../src/domain/javascriptSemanticQuerySchemas.js";
const SHA = "a".repeat(64);
const JAG_ID = `jag_${"b".repeat(64)}`;
const completeCoverage = {
status: "complete" as const,
truncated: false,
omitted_count: 0,
limits: [],
};
const evidence = (
state: "observed" | "inferred" = "observed",
): ApplicationGraphEvidence => ({
authority:
state === "observed"
? "ast-static-analysis"
: "static-relationship-inference",
state,
confidence: state === "observed" ? "exact" : "high",
artifact: { available: true, artifact_id: `art_${SHA}`, sha256: SHA },
location: {
available: true,
value: {
kind: "source-range",
source: "bundle.js",
start: { line: 1, column: 0 },
end: { line: 1, column: 10 },
},
},
extractor: {
name: "test",
version: "1",
operation: "recover-semantic-relation",
executable_sha256: null,
},
coverage: completeCoverage,
limitations:
state === "observed"
? []
: ["Static reachability does not prove runtime execution."],
evidence_ids: [],
});
const unknownEvidence = (): ApplicationGraphEvidence => ({
authority: "unknown",
state: "unknown",
confidence: "unknown",
artifact: {
available: false,
reason: "unknown",
detail: "Unknown artifact.",
},
location: {
available: false,
reason: "unresolved",
detail: "Dynamic call target.",
},
extractor: {
name: "test",
version: "1",
operation: "retain-dynamic-call",
executable_sha256: null,
},
coverage: {
status: "unknown",
truncated: false,
omitted_count: null,
limits: [],
},
limitations: ["Dynamic call target remains unknown."],
evidence_ids: [],
});
const node = (
kind: (typeof JAVASCRIPT_SEMANTIC_NODE_KINDS)[number],
role: string,
properties: Record<string, string | number | boolean | null> = {},
functionNodeId: string | null = null,
): JavaScriptSemanticGraphNode =>
createJavaScriptSemanticGraphNode({
kind,
identity: {
artifact_sha256: SHA,
module_path: "bundle.js",
source_range: {
start: { line: 1, column: role.length },
end: { line: 1, column: role.length + 1 },
},
role_key: role,
},
function_node_id: functionNodeId,
application_node_ids: [],
label: role,
properties,
evidence: evidence(),
});
const fixtureGraph = (withUnknown = false): JavaScriptSemanticGraph => {
const module = node("module", "module");
const literal = node("literal", "literal", { value: "TOKEN" });
const binding = node("binding", "binding");
const callable = node("function", "function");
const request = node("request", "request", {
endpoint: "https://example.invalid/v1",
});
const relations = [
createJavaScriptSemanticGraphRelation({
source_node_id: literal.node_id,
target_node_id: binding.node_id,
relation: "defines",
resolution: "resolved",
properties: {},
evidence: evidence("inferred"),
}),
createJavaScriptSemanticGraphRelation({
source_node_id: binding.node_id,
target_node_id: callable.node_id,
relation: "captures",
resolution: "resolved",
properties: {},
evidence: evidence("inferred"),
}),
createJavaScriptSemanticGraphRelation({
source_node_id: callable.node_id,
target_node_id: request.node_id,
relation: "constructs-request",
resolution: "resolved",
properties: {},
evidence: evidence("inferred"),
}),
];
const dynamic = createJavaScriptSemanticGraphUnknown({
node_id: callable.node_id,
family: "call-flow",
relation_kinds: ["calls"],
reason: "dynamic-call",
detail: "Computed callee is unresolved.",
candidate_node_ids: [],
evidence: unknownEvidence(),
});
const unknowns = withUnknown ? [dynamic] : [];
const coverageFamilies = JAVASCRIPT_SEMANTIC_RELATION_FAMILIES.map(
(family) => ({
family,
status:
withUnknown && family === "call-flow"
? ("unknown" as const)
: ("complete" as const),
retained_relations: relations.filter(({ relation }) =>
relation === "defines"
? family === "data-flow"
: relation === "captures"
? family === "closure"
: family === "request",
).length,
omitted_relations: withUnknown && family === "call-flow" ? null : 0,
unknown_ids:
withUnknown && family === "call-flow" ? [dynamic.unknown_id] : [],
}),
);
const fingerprint = createJavaScriptSemanticFingerprint({
function_node_id: callable.node_id,
algorithm: "rea.javascript-semantic-function/v1",
status: "complete",
components: {
parameter_arity: 0,
normalized_ast_sha256: "1".repeat(64),
control_flow_sha256: "2".repeat(64),
relation_shape_sha256: "3".repeat(64),
literal_set_sha256: "4".repeat(64),
effects: ["network"],
},
limitations: [],
evidence: evidence("inferred"),
});
return createJavaScriptSemanticGraph({
schema: "JavaScriptSemanticRelationGraph",
schema_version: 1,
root_artifact_sha256: SHA,
application_graph_id: JAG_ID,
root_node_ids: [module.node_id],
nodes: [request, callable, binding, literal, module],
relations,
fingerprints: [fingerprint],
unknowns,
coverage: {
status: withUnknown ? "partial" : "complete",
truncated: false,
omitted_nodes: withUnknown ? null : 0,
omitted_relations: withUnknown ? null : 0,
limits: [],
families: coverageFamilies,
},
limitations: withUnknown ? ["Dynamic call target remains unknown."] : [],
});
};
const graphWithCandidateEdge = (): JavaScriptSemanticGraph => {
const graph = fixtureGraph();
const literal = graph.nodes.find(({ kind }) => kind === "literal");
const request = graph.nodes.find(({ kind }) => kind === "request");
if (literal === undefined || request === undefined)
throw new TypeError("Semantic fixture nodes are missing");
const candidate = createJavaScriptSemanticGraphRelation({
source_node_id: literal.node_id,
target_node_id: request.node_id,
relation: "supplies-request-field",
resolution: "candidate",
properties: { field: "authorization" },
evidence: evidence("inferred"),
});
const { graph_id: _graphId, ...input } = graph;
return createJavaScriptSemanticGraph({
...input,
relations: [...graph.relations, candidate],
coverage: {
...graph.coverage,
families: graph.coverage.families.map((family) =>
family.family === "request"
? {
...family,
retained_relations: family.retained_relations + 1,
}
: family,
),
},
});
};
const graphWithDuplicateLiteral = (): JavaScriptSemanticGraph => {
const graph = fixtureGraph();
const duplicate = node("literal", "literal-copy", { value: "TOKEN" });
const { graph_id: _graphId, ...input } = graph;
return createJavaScriptSemanticGraph({
...input,
nodes: [...graph.nodes, duplicate],
});
};
it("bounds relevant unknown frontiers independently from relation pages", () => {
const graph = fixtureGraph(true);
const callable = graph.nodes.find(({ kind }) => kind === "function");
if (callable === undefined) throw new Error("Expected callable node");
const result = queryJavaScriptSemanticGraph(graph, {
seed: { kind: "semantic-node", node_id: callable.node_id },
direction: "forward-influence",
limits: { max_unknowns: 0 },
});
expect(result).toMatchObject({
status: "truncated",
unknowns: [],
summary: { relevant_unknowns: 1, retained_unknowns: 0 },
coverage: { status: "truncated" },
});
});
it("traces deterministic forward influence and pages without changing identity", () => {
const graph = fixtureGraph();
const input = {
seed: { kind: "literal" as const, value: "TOKEN" },
direction: "forward-influence" as const,
expected: { role: "sink" as const, classes: ["request" as const] },
limits: {
max_seed_matches: 25,
max_nodes: 20,
max_edges: 20,
max_depth: 12,
max_functions: 10,
max_modules: 10,
page_size: 2,
},
};
const first = queryJavaScriptSemanticGraph(graph, input);
expect(first).toMatchObject({
status: "found",
summary: { traversed_nodes: 4, traversed_relations: 3 },
page: { offset: 0, size: 2 },
});
expect(first.expected_match_node_ids).toHaveLength(1);
expect(first.page.next_cursor).not.toBeNull();
const second = queryJavaScriptSemanticGraph(graph, {
...input,
cursor: first.page.next_cursor,
});
expect(second.query_id).toBe(first.query_id);
expect(second.page).toMatchObject({
offset: 2,
size: 1,
next_cursor: null,
});
expect(second.relations[0]?.relation_id).not.toBe(
first.relations[0]?.relation_id,
);
});
it("keeps relevant dynamic frontiers unknown", () => {
const result = queryJavaScriptSemanticGraph(fixtureGraph(true), {
seed: { kind: "literal", value: "TOKEN" },
direction: "forward-influence",
});
expect(result.status).toBe("found");
expect(result.coverage.status).toBe("partial");
expect(result.unknowns).toMatchObject([
{ reason: "dynamic-call", relation_kinds: ["calls"] },
]);
});
it("excludes candidate edges unless the caller explicitly opts in", () => {
const graph = graphWithCandidateEdge();
const input = {
seed: { kind: "literal" as const, value: "TOKEN" },
direction: "forward-influence" as const,
allowed_relations: ["supplies-request-field" as const],
};
const conservative = queryJavaScriptSemanticGraph(graph, input);
const optedIn = queryJavaScriptSemanticGraph(graph, {
...input,
include_ambiguous_dynamic_edges: true,
});
expect(conservative.summary.traversed_relations).toBe(0);
expect(optedIn.summary.traversed_relations).toBe(1);
expect(conservative.status).toBe("ambiguous");
expect(conservative.coverage.status).toBe("partial");
expect(optedIn.status).toBe("ambiguous");
expect(optedIn.relations).toMatchObject([
{ relation: "supplies-request-field", resolution: "candidate" },
]);
});
it("bounds seed ambiguity before traversal", () => {
const result = queryJavaScriptSemanticGraph(graphWithDuplicateLiteral(), {
seed: { kind: "literal", value: "TOKEN" },
direction: "forward-influence",
limits: {
max_seed_matches: 1,
max_nodes: 20,
max_edges: 20,
max_depth: 12,
max_functions: 10,
max_modules: 10,
page_size: 10,
},
});
expect(result.summary).toMatchObject({
total_seed_matches: 2,
retained_seed_matches: 1,
});
expect(result.status).toBe("truncated");
expect(result.coverage.frontier).toContainEqual(
expect.objectContaining({ reason: "max-seed-matches", depth: 0 }),
);
});
it("reports exact caller limits and a deterministic truncation frontier", () => {
const result = queryJavaScriptSemanticGraph(fixtureGraph(), {
seed: { kind: "literal", value: "TOKEN" },
direction: "forward-influence",
limits: {
max_seed_matches: 1,
max_nodes: 2,
max_edges: 10,
max_depth: 12,
max_functions: 10,
max_modules: 10,
page_size: 10,
},
});
expect(result.status).toBe("truncated");
expect(result.coverage.frontier).toMatchObject([{ reason: "max-nodes" }]);
expect(result.applied_limits.max_nodes).toBe(2);
expect(result.accepted_limit_ranges.max_nodes).toEqual({
minimum: 1,
maximum: 50_000,
});
});
it.each([
{
limit: { max_edges: 1 },
reason: "max-edges",
},
{
limit: { max_depth: 0 },
reason: "max-depth",
},
])("reports the $reason frontier", ({ limit, reason }) => {
const result = queryJavaScriptSemanticGraph(fixtureGraph(), {
seed: { kind: "literal", value: "TOKEN" },
direction: "forward-influence",
limits: {
max_seed_matches: 10,
max_nodes: 20,
max_edges: limit.max_edges ?? 20,
max_depth: limit.max_depth ?? 12,
max_functions: 10,
max_modules: 10,
page_size: 10,
},
});
expect(result.status).toBe("truncated");
expect(result.coverage.frontier).toContainEqual(
expect.objectContaining({ reason }),
);
});
it("rejects out-of-range limits and cursors from another query", () => {
expect(() =>
javaScriptSemanticQueryInputSchema.parse({
seed: { kind: "literal", value: "TOKEN" },
direction: "forward-influence",
limits: { max_nodes: 50_001 },
}),
).toThrow();
const graph = fixtureGraph();
const first = queryJavaScriptSemanticGraph(graph, {
seed: { kind: "literal", value: "TOKEN" },
direction: "forward-influence",
limits: { page_size: 1 },
});
expect(() =>
queryJavaScriptSemanticGraph(graph, {
seed: { kind: "endpoint", value: "https://example.invalid/v1" },
direction: "backward-provenance",
limits: { page_size: 1 },
cursor: first.page.next_cursor,
}),
).toThrow(/cursor does not match/u);
});
@@ -0,0 +1,289 @@
import { describe, expect, it } from "vitest";
import {
computeHistoricalSourceGraphSha256,
createHistoricalSourceGraph,
createHistoricalSourceManifest,
historicalSourceGraphSchema,
historicalSourceParseFailureKey,
parseHistoricalSourceGraph,
parseHistoricalSourceManifest,
type HistoricalSourceGraphInput,
} from "../../../src/domain/referenceSourceGraph.js";
const HASH_A = "a".repeat(64);
const HASH_B = "b".repeat(64);
type Entry = HistoricalSourceGraphInput["entries"][number];
type DirectoryEntry = Extract<Entry, { kind: "directory" }>;
type FileEntry = Extract<Entry, { kind: "file" }>;
type SymlinkEntry = Extract<Entry, { kind: "symlink" }>;
const directoryEntry = (
treeState: DirectoryEntry["tree_state"] = "enumerated",
): DirectoryEntry => ({
path: "src",
kind: "directory",
classifications: ["source"],
tree_state: treeState,
limitations: [],
});
const fileEntry = (overrides: Partial<FileEntry> = {}): FileEntry => ({
path: "src/main.ts",
kind: "file",
sha256: HASH_B,
size: 20,
language: "TypeScript",
classifications: ["source"],
content_state: "hashed",
limitations: [],
...overrides,
});
const symlinkEntry = (overrides: Partial<SymlinkEntry> = {}): SymlinkEntry => ({
path: "src/package.json",
kind: "symlink",
target: "main.ts",
target_state: "internal",
classifications: ["manifest"],
limitations: [],
...overrides,
});
const graphInput = (): HistoricalSourceGraphInput => ({
schema: "HistoricalSourceGraph/v1",
authority: "historical-reference",
root_alias: "$REFERENCE_ROOT",
inventory_state: "complete",
entries: [directoryEntry(), fileEntry(), symlinkEntry()],
relationships: [
{
from_path: "src/main.ts",
to: "node:fs",
kind: "imports",
resolution: "external",
parse_state: "parsed",
},
{
from_path: "src/main.ts",
to: "src",
kind: "references",
resolution: "internal",
parse_state: "parsed",
},
],
parse_failures: [],
exclusions: [],
languages: ["TypeScript"],
manifests: [],
vcs: { kind: "git", head: HASH_A, dirty: false },
provenance: { importer: "rea", importer_version: "1", caller: "test" },
limitations: [],
});
describe("historical source graph", () => {
it("builds and verifies internal root and manifest commitments", () => {
const graph = createHistoricalSourceGraph(graphInput());
const first = createHistoricalSourceManifest(graph);
const second = createHistoricalSourceManifest(structuredClone(graph));
expect(first).toEqual(second);
expect(parseHistoricalSourceGraph(graph)).toEqual(graph);
expect(parseHistoricalSourceManifest(first)).toEqual(first);
expect(first.graph_sha256).toBe(computeHistoricalSourceGraphSha256(graph));
});
it("rejects stale roots and commits file, directory, and symlink semantics", () => {
const original = createHistoricalSourceGraph(graphInput());
expect(() =>
parseHistoricalSourceGraph({ ...original, root_sha256: HASH_A }),
).toThrow(/root commitment/u);
for (const mutate of [
(input: HistoricalSourceGraphInput) => {
input.entries[0] = directoryEntry("partial");
input.inventory_state = "partial";
},
(input: HistoricalSourceGraphInput) => {
input.entries[1] = fileEntry({ sha256: "c".repeat(64) });
},
(input: HistoricalSourceGraphInput) => {
input.entries[2] = symlinkEntry({
target: "other.json",
target_state: "missing",
});
input.inventory_state = "partial";
},
(input: HistoricalSourceGraphInput) => {
input.exclusions = [
{ path: "private.env", reason: "configured-secret" },
];
input.inventory_state = "partial";
},
]) {
const changed = graphInput();
mutate(changed);
expect(createHistoricalSourceGraph(changed).root_sha256).not.toBe(
original.root_sha256,
);
}
});
it("derives language and manifest indexes and enforces code-point order", () => {
const input = graphInput();
input.entries[1] = fileEntry({ classifications: ["source", "test"] });
expect(() =>
createHistoricalSourceGraph({ ...input, languages: [] }),
).toThrow(/derived/u);
expect(() =>
createHistoricalSourceGraph({ ...input, manifests: ["src/main.ts"] }),
).toThrow(/derived/u);
expect(() =>
createHistoricalSourceGraph({
...input,
entries: input.entries.toReversed(),
}),
).toThrow(/Unicode code point/u);
expect(() =>
createHistoricalSourceGraph({
...input,
entries: input.entries.map((entry) =>
entry.path === "src/main.ts"
? { ...entry, classifications: ["test", "source"] }
: entry,
),
}),
).toThrow(/Unicode code point/u);
});
});
describe("partial historical source graphs", () => {
it("preserves partial observations but rejects every partial complete graph", () => {
const partial = graphInput();
partial.inventory_state = "partial";
partial.entries[1] = fileEntry({
sha256: null,
size: null,
content_state: "unreadable",
limitations: ["Permission denied"],
});
partial.parse_failures = [
{ path: "src/main.ts", parser: "typescript", reason: "Malformed input" },
];
expect(createHistoricalSourceGraph(partial).inventory_state).toBe(
"partial",
);
for (const change of [
{ entries: partial.entries },
{ parse_failures: partial.parse_failures },
{
exclusions: [{ path: "secret", reason: "configured-secret" as const }],
},
{ limitations: ["Incomplete"] },
{
relationships: [
{
...graphInput().relationships[0]!,
parse_state: "partial" as const,
},
],
},
])
expect(() =>
createHistoricalSourceGraph({ ...graphInput(), ...change }),
).toThrow(/Complete inventory/u);
});
it("keeps distinct parse failure reasons for the same path and parser", () => {
const input = graphInput();
const malformed = {
path: "src/main.ts",
parser: "typescript",
reason: "Malformed input",
};
const unexpected = {
path: "src/main.ts",
parser: "typescript",
reason: "Unexpected token",
};
input.inventory_state = "partial";
input.parse_failures = [malformed, unexpected];
expect(createHistoricalSourceGraph(input).parse_failures).toEqual(
input.parse_failures,
);
expect(historicalSourceParseFailureKey(malformed)).not.toBe(
historicalSourceParseFailureKey(unexpected),
);
});
});
describe("historical source graph validation", () => {
it("rejects strict unknown fields, invalid VCS, dangling internal edges, and false manifests", () => {
expect(() =>
createHistoricalSourceGraph({ ...graphInput(), surprise: true }),
).toThrow();
expect(() =>
createHistoricalSourceGraph({
...graphInput(),
vcs: { kind: "git", head: "main", dirty: false },
}),
).toThrow();
expect(() =>
createHistoricalSourceGraph({
...graphInput(),
relationships: [
{ ...graphInput().relationships[1]!, to: "missing.ts" },
],
}),
).toThrow(/normalized and inventoried/u);
expect(() =>
createHistoricalSourceGraph({
...graphInput(),
inventory_state: "partial",
entries: graphInput().entries.map((entry) =>
entry.kind === "symlink"
? { ...entry, target: "/etc/passwd", target_state: "external" }
: entry,
),
}),
).toThrow();
expect(() =>
createHistoricalSourceGraph({
...graphInput(),
inventory_state: "partial",
entries: graphInput().entries.map((entry) =>
entry.kind === "symlink"
? {
...entry,
target: "<outside-root>",
target_state: "external",
}
: entry,
),
}),
).not.toThrow();
expect(() =>
createHistoricalSourceGraph({
...graphInput(),
relationships: [
{ ...graphInput().relationships[1]!, to: "../escape.ts" },
],
}),
).toThrow(/normalized and inventoried/u);
expect(() =>
historicalSourceGraphSchema.parse({
...createHistoricalSourceGraph(graphInput()),
extra: true,
}),
).toThrow();
const manifest = createHistoricalSourceManifest(
createHistoricalSourceGraph(graphInput()),
);
expect(() =>
parseHistoricalSourceManifest({ ...manifest, entry_count: 999 }),
).toThrow(/identifier does not match/u);
});
});
@@ -0,0 +1,320 @@
import { describe, expect, it } from "vitest";
import {
createJavaScriptApplicationGraph,
createJavaScriptApplicationNode,
} from "../../../src/domain/javascriptApplicationGraph.js";
import { createHistoricalSourceGraph } from "../../../src/domain/referenceSourceGraph.js";
import { compareSourceToBundle } from "../../../src/domain/sourceToBundleComparison.js";
import { sourceToBundleComparisonResultSchema } from "../../../src/domain/sourceToBundleComparisonSchemas.js";
import { artifactEvidence } from "../../fixtures/javascriptApplicationGraph.js";
const HASH = {
artifact: "1".repeat(64),
unchanged: "2".repeat(64),
modified: "3".repeat(64),
removed: "4".repeat(64),
split: "5".repeat(64),
merged: "6".repeat(64),
duplicated: "7".repeat(64),
} as const;
const EVIDENCE_ID = `ev_${"a".repeat(64)}`;
describe("historical source to bundle comparison", () => {
it("classifies exact, changed, absent, split, and merged mappings stably", () => {
const reference = historicalGraph("complete");
const graph = applicationGraph("complete");
const input = {
reference,
application: {
evidenceId: EVIDENCE_ID,
rootArtifactSha256: HASH.artifact,
graph,
},
limits: limits(),
};
const first = compareSourceToBundle(input);
const second = compareSourceToBundle(input);
expect(first).toEqual(second);
expect(() =>
sourceToBundleComparisonResultSchema.parse(first),
).not.toThrow();
expect(first.summary).toEqual({
unchanged: 1,
modified: 0,
removed: 1,
split: 1,
merged: 2,
duplicated: 1,
unknown: 1,
});
expect(item(first, "src/unchanged.ts")).toMatchObject({
status: "unchanged",
confidence: "exact",
candidates: [
expect.objectContaining({
signals: expect.arrayContaining([
expect.objectContaining({
kind: "exact-source-digest",
weight: 100,
}),
]),
}),
],
});
expect(item(first, "src/modified.ts")).toMatchObject({
status: "unknown",
confidence: "unknown",
candidates: [
expect.objectContaining({
signals: expect.arrayContaining([
expect.objectContaining({ kind: "current-path-exact", weight: 60 }),
]),
}),
],
});
expect(item(first, "src/removed.ts")).toMatchObject({
status: "removed",
current_node_ids: [],
});
expect(item(first, "src/split.ts")).toMatchObject({
status: "split",
confidence: "medium",
current_node_ids: [expect.any(String), expect.any(String)],
});
expect(item(first, "src/merged-a.ts").status).toBe("merged");
expect(item(first, "src/merged-b.ts").status).toBe("merged");
expect(item(first, "src/duplicated.ts")).toMatchObject({
status: "duplicated",
confidence: "exact",
current_node_ids: [expect.any(String), expect.any(String)],
});
expect(first.coverage.status).toBe("complete-within-inputs");
});
it("keeps absence unknown when either inventory is incomplete", () => {
const reference = historicalGraph("partial", ["src/removed.ts"]);
const graph = applicationGraph("partial");
const result = compareSourceToBundle({
reference,
application: {
evidenceId: EVIDENCE_ID,
rootArtifactSha256: HASH.artifact,
graph,
},
limits: limits(),
});
expect(result.summary).toMatchObject({ removed: 0, unknown: 1 });
expect(result.items[0]).toMatchObject({
source_path: "src/removed.ts",
status: "unknown",
confidence: "unknown",
});
expect(result.coverage.status).toBe("partial");
});
it("keeps exact mappings unknown when candidate output is truncated", () => {
const result = compareSourceToBundle({
reference: historicalGraph("complete"),
application: {
evidenceId: EVIDENCE_ID,
rootArtifactSha256: HASH.artifact,
graph: applicationGraph("complete"),
},
limits: { ...limits(), max_candidate_nodes: 1 },
});
expect(item(result, "src/duplicated.ts").status).toBe("unknown");
expect(
item(result, "src/duplicated.ts").omitted_candidates,
).toBeGreaterThan(0);
});
it("reports the candidate frontier instead of deciding past a limit", () => {
const result = compareSourceToBundle({
reference: historicalGraph("complete", ["src/split.ts"]),
application: {
evidenceId: EVIDENCE_ID,
rootArtifactSha256: HASH.artifact,
graph: applicationGraph("complete"),
},
limits: { ...limits(), max_candidate_evaluations: 1 },
});
expect(result.items[0]).toMatchObject({
status: "unknown",
confidence: "unknown",
omitted_candidates: 1,
});
expect(result.coverage).toMatchObject({
status: "truncated",
candidate_evaluations: 1,
omitted_candidate_evaluations: 1,
});
});
});
const historicalGraph = (
inventoryState: "complete" | "partial",
paths = [
"src/duplicated.ts",
"src/merged-a.ts",
"src/merged-b.ts",
"src/modified.ts",
"src/removed.ts",
"src/split.ts",
"src/unchanged.ts",
],
) =>
createHistoricalSourceGraph({
schema: "HistoricalSourceGraph/v1",
authority: "historical-reference",
root_alias: "$REFERENCE_ROOT",
inventory_state: inventoryState,
entries: [
{
path: "src",
kind: "directory",
classifications: ["source"],
tree_state: inventoryState === "complete" ? "enumerated" : "partial",
limitations:
inventoryState === "complete"
? []
: ["Fixture inventory is partial."],
},
...paths.map((path) => ({
path,
kind: "file" as const,
sha256: sourceDigest(path),
size: 10,
language: "TypeScript",
classifications: ["source"] as const,
content_state: "hashed" as const,
limitations: [],
})),
],
relationships: [],
parse_failures: [],
exclusions: [],
languages: ["TypeScript"],
manifests: [],
vcs: { kind: "none", head: null, dirty: null },
provenance: {
importer: "rea-test",
importer_version: "1",
caller: "source-to-bundle-test",
},
limitations:
inventoryState === "complete" ? [] : ["Fixture inventory is partial."],
});
const applicationGraph = (coverage: "complete" | "partial") => {
const nodes = [
moduleNode("duplicated-a", {
path: "bundle-a.js",
source_sha256: HASH.duplicated,
}),
moduleNode("duplicated-b", {
path: "bundle-b.js",
source_sha256: HASH.duplicated,
}),
moduleNode("unchanged", {
path: "bundle.js",
source_sha256: HASH.unchanged,
}),
createJavaScriptApplicationNode({
kind: "javascript-asset",
identity: {
strategy: "canonical-path",
stability: "artifact-version",
artifact_sha256: HASH.artifact,
path: "src/modified.ts",
},
observations: [
{
label: "src/modified.ts",
properties: { path: "src/modified.ts" },
evidence: artifactEvidence(HASH.artifact, "src/modified.ts"),
},
],
}),
moduleNode("split-a", { path: "bundle-a/src/split.ts" }),
moduleNode("split-b", { path: "bundle-b/src/split.ts" }),
moduleNode("merged", {
path: "bundle.js",
source_sha256: HASH.merged,
}),
];
return createJavaScriptApplicationGraph({
schema: "JavaScriptApplicationGraph",
schema_version: 1,
root_node_ids: nodes.map(({ node_id: nodeId }) => nodeId),
nodes,
edges: [],
coverage:
coverage === "complete"
? {
status: "complete",
truncated: false,
omitted_count: 0,
limits: [],
}
: {
status: "partial",
truncated: true,
omitted_count: 1,
limits: [{ name: "fixture", value: 5, unit: "items" }],
},
limitations:
coverage === "complete" ? [] : ["Fixture graph coverage is partial."],
});
};
const moduleNode = (key: string, properties: Record<string, string>) =>
createJavaScriptApplicationNode({
kind: "javascript-module",
identity: {
strategy: "artifact-local-key",
stability: "artifact-version",
artifact_sha256: HASH.artifact,
namespace: "test",
key,
},
observations: [
{
label: key,
properties,
evidence: artifactEvidence(HASH.artifact, "bundle.js"),
},
],
});
const sourceDigest = (path: string): string => {
if (path.includes("duplicated")) return HASH.duplicated;
if (path.includes("merged")) return HASH.merged;
if (path.includes("modified")) return HASH.modified;
if (path.includes("removed")) return HASH.removed;
if (path.includes("split")) return HASH.split;
return HASH.unchanged;
};
const limits = () => ({
max_source_files: 100,
max_application_nodes: 100,
max_candidate_nodes: 100,
max_candidate_evaluations: 10_000,
});
const item = (
result: ReturnType<typeof compareSourceToBundle>,
sourcePath: string,
) => {
const value = result.items.find(
({ source_path: path }) => path === sourcePath,
);
if (value === undefined) throw new TypeError(`Missing item: ${sourcePath}`);
return value;
};
@@ -0,0 +1,267 @@
import { describe, expect, it } from "vitest";
import {
inspectWebPageInputSchema,
webPageInspectionSchema,
} from "../../../src/domain/browserObservation.js";
import { analyzeCapturedWebBundle } from "../../../src/domain/webBundleAnalyzer.js";
import {
analyzeWebBundleInputSchema,
webBundleAnalysisSchema,
} from "../../../src/domain/webBundleAnalysis.js";
import { createWebTextArtifact } from "../../../src/domain/webContentArtifact.js";
const origin = "https://app.example.test";
describe("web bundle analyzer", () => {
it("extracts bounded graph, route, endpoint, vendor, and WebMCP evidence", () => {
const source = `
import { createApp } from "./chunk.js?token=secret";
const lazy = import("./lazy.js");
const routes = [{ path: "/users/:id?token=secret" }];
fetch("/api/users?authorization=secret");
document.modelContext.registerTool({
name: "lookup-user",
description: "Untrusted page declaration",
inputSchema: {
type: "object",
properties: {
userId: { type: "string" },
verbose: { type: "boolean" }
}
}
});
const __webpack_require__ = () => createApp(routes, lazy);
`;
const result = analyzeCapturedWebBundle(inspection(source), input());
expect(result.observations.chunks.edges).toEqual(
expect.arrayContaining([
expect.objectContaining({
kind: "static_import",
specifier: "./chunk.js?token=secret",
resolved_url: `${origin}/assets/chunk.js?token=%5BREDACTED%5D`,
}),
expect.objectContaining({
kind: "dynamic_import",
specifier: "./lazy.js",
}),
]),
);
expect(result.observations.routes).toEqual([
expect.objectContaining({ value: "/users/:id?token=%5BREDACTED%5D" }),
]);
expect(result.observations.endpoints).toEqual([
expect.objectContaining({
value: "/api/users?authorization=%5BREDACTED%5D",
}),
]);
expect(result.observations.webmcp_declarations).toEqual([
expect.objectContaining({
name: "lookup-user",
trust: "page-declared-untrusted",
schema_property_names: ["userId", "verbose"],
}),
]);
expect(result.inferences).toEqual(
expect.arrayContaining([
expect.objectContaining({ value: "webpack", confidence: "high" }),
expect.objectContaining({ value: "Vue" }),
]),
);
expect(JSON.stringify(result)).not.toContain("authorization=secret");
expect(result.completeness.status).toBe("complete_within_limits");
});
it("reports parser gaps and finding truncation instead of claiming completeness", () => {
const malformed = inspection("function broken( {");
const failed = analyzeCapturedWebBundle(malformed, input());
expect(failed.completeness).toMatchObject({
status: "partial",
parse_failures: 1,
});
expect(failed.unknowns[0]?.dimension).toBe("javascript_ast");
const bounded = analyzeCapturedWebBundle(
inspection("fetch('/one'); fetch('/two'); fetch('/three');"),
input({ analysis_limits: { max_findings: 1 } }),
);
expect(bounded.observations.endpoints).toHaveLength(1);
expect(bounded.completeness).toMatchObject({
status: "truncated",
dropped_findings: 2,
});
});
it("propagates source-map truncation into completeness and unknowns", () => {
const analysis = analyzeCapturedWebBundle(
inspection("export {};"),
input(),
{
status: "truncated",
requested: 2,
processed: 1,
dropped: 1,
dropped_script_keys: [`scr_${"2".repeat(64)}`],
items: [
{
script_key: `scr_${"1".repeat(64)}`,
declared_url: "https://app.example.test/app.js.map",
status: "truncated",
artifact: null,
original_sources: [],
original_module_edges: [],
mappings: [],
limitation: "Source-map response exceeded the byte budget.",
},
],
},
);
expect(analysis.completeness.status).toBe("truncated");
expect(analysis.unknowns).toContainEqual({
dimension: "source_maps",
reason: "Source-map evidence was truncated by approved limits",
affected_script_keys: [`scr_${"1".repeat(64)}`, `scr_${"2".repeat(64)}`],
});
});
it("rejects inconsistent source-map coverage counts", () => {
const result = analyzeCapturedWebBundle(inspection("export {};"), input());
expect(
webBundleAnalysisSchema.safeParse({
...result,
observations: {
...result.observations,
source_maps: {
...result.observations.source_maps,
requested: 1,
},
},
}).success,
).toBe(false);
});
});
const input = (overrides: Record<string, unknown> = {}) =>
analyzeWebBundleInputSchema.parse({
...inspectWebPageInputSchema.parse({
cdp_endpoint: "http://127.0.0.1:9222",
allowed_origins: [origin],
target_id: "page-1",
approved: true,
include_script_sources: true,
}),
source_capture_approved: true,
...overrides,
});
const inspection = (source: string) =>
webPageInspectionSchema.parse({
schema_version: 2,
browser: {
product: "Fake Chrome",
protocol_version: "1.3",
revision: "1",
user_agent: "fake",
js_version: "1",
},
target: {
target_id: "page-1",
type: "page",
title: "App",
url: `${origin}/app`,
origin,
attached: false,
},
capture_window: {
started_at: "2026-07-14T00:00:00.000Z",
ended_at: "2026-07-14T00:00:01.000Z",
observation_ms: 1_000,
},
completeness: {
status: "attach_limited",
conditions: ["attach_limited"],
policy_filtered_sections: [],
attach_limited_sections: ["network_requests"],
truncated_sections: [],
unavailable_sections: [],
excluded: [],
dropped_events: {
scripts: 0,
network_requests: 0,
console_events: 0,
websocket_connections: 0,
websocket_frames: 0,
webmcp_tools: 0,
timeline_events: 0,
total: 0,
},
},
frames: [],
dom: { total_nodes: 0, nodes: [] },
accessibility: {
total_nodes: 0,
text_capture: {
status: "not_approved",
retained_bytes: 0,
excluded_fields: 0,
truncated_fields: 0,
},
nodes: [],
},
scripts: {
total: 1,
items: [
{
script_key: `scr_${"1".repeat(64)}`,
url: `${origin}/assets/app.js`,
origin,
cdp_hash: "hash",
length: Buffer.byteLength(source),
is_module: true,
language: "JavaScript",
source_map_url: null,
resource_reconciliation: {
status: "unmatched",
reason: "no_exact_sanitized_url",
},
source: {
included: true,
artifact: createWebTextArtifact(source, "text/javascript"),
},
},
],
},
resources: [],
network: {
requests: [],
websocket_events: [],
coverage_started_at: "2026-07-14T00:00:00.000Z",
prior_activity_available: false,
},
console: {
events: [],
coverage_started_at: "2026-07-14T00:00:00.000Z",
prior_activity_available: false,
},
workers: [],
metadata: {
responses: [],
dom_urls: [],
agent_hints: [],
excluded_dom_urls: 0,
headers_allowlisted: true,
},
storage: {
origin,
usage_bytes: null,
quota_bytes: null,
local_storage_keys: [],
session_storage_keys: [],
indexed_db_names: [],
cache_names: [],
values_redacted: true,
},
limitations: [],
});
@@ -0,0 +1,154 @@
import { describe, expect, it } from "vitest";
import {
reconcileCapturedWebScript,
reconcileWebScript,
stableWebResources,
stableWebScriptKey,
} from "../../../src/domain/webInventory.js";
import {
createWebTextArtifact,
webTextArtifactSchema,
} from "../../../src/domain/webContentArtifact.js";
describe("web content artifacts", () => {
it("binds UTF-8 content, size, digest, and URI", () => {
const artifact = createWebTextArtifact(
"const marker = '😀';",
"text/javascript",
);
expect(webTextArtifactSchema.parse(artifact)).toEqual(artifact);
expect(artifact.bytes).toBe(Buffer.byteLength(artifact.text));
expect(artifact.uri).toBe(`rea://web-content/sha256/${artifact.sha256}`);
});
it("rejects altered content that reuses an artifact digest", () => {
const artifact = createWebTextArtifact("original", "text/javascript");
expect(
webTextArtifactSchema.safeParse({ ...artifact, text: "altered!" })
.success,
).toBe(false);
});
});
describe("stable web inventory", () => {
const script = {
url: "https://app.example.test/assets/app.js",
cdp_hash: "stable-cdp-hash",
length: 1_024,
is_module: true,
language: "JavaScript",
source_map_url: "https://app.example.test/assets/app.js.map",
};
it("excludes transient CDP and target identity from script keys", () => {
expect(stableWebScriptKey(script)).toBe(stableWebScriptKey({ ...script }));
expect(stableWebScriptKey({ ...script, length: 1_025 })).not.toBe(
stableWebScriptKey(script),
);
});
it("sorts resources deterministically and reconciles only exact URLs", () => {
const inputs = [
{
url: "https://app.example.test/assets/vendor.js",
origin: "https://app.example.test",
type: "Script",
mime_type: "text/javascript",
content_size: 200,
},
{
url: script.url,
origin: "https://app.example.test",
type: "Script",
mime_type: "text/javascript",
content_size: 1_024,
},
];
const forward = stableWebResources(inputs);
const reverse = stableWebResources([...inputs].reverse());
expect(reverse).toEqual(forward);
expect(reconcileWebScript(script, forward)).toEqual({
status: "exact",
resource_key: forward.find(({ url }) => url === script.url)?.resource_key,
});
expect(
reconcileWebScript({ ...script, url: `${script.url}?v=2` }, forward),
).toEqual({ status: "unmatched", reason: "no_exact_sanitized_url" });
});
it("reports duplicate resource observations as ambiguous", () => {
const duplicate = {
url: script.url,
origin: "https://app.example.test",
type: "Script",
mime_type: "text/javascript",
content_size: 1_024,
};
const resources = stableWebResources([
duplicate,
{ ...duplicate, content_size: 2_048 },
]);
expect(reconcileWebScript(script, resources)).toEqual({
status: "ambiguous",
candidate_resource_keys: resources
.map(({ resource_key }) => resource_key)
.sort(),
});
});
it("deduplicates identical resource observations by stable identity", () => {
const duplicate = {
url: script.url,
origin: "https://app.example.test",
type: "Script",
mime_type: "text/javascript",
content_size: 1_024,
};
expect(stableWebResources([duplicate, duplicate])).toEqual(
stableWebResources([duplicate]),
);
});
it("reconciles raw URLs independently of stable inventory sort order", () => {
const app = {
url: script.url,
origin: "https://app.example.test",
type: "Script",
mime_type: "text/javascript",
content_size: 1_024,
rawUrl: `${script.url}?token=secret`,
};
const vendor = {
url: "https://app.example.test/assets/vendor.js",
origin: "https://app.example.test",
type: "Script",
mime_type: "text/javascript",
content_size: 2_048,
rawUrl: "https://app.example.test/assets/vendor.js?v=1",
};
for (const rawResources of [
[app, vendor],
[vendor, app],
]) {
const resources = stableWebResources(
rawResources.map(({ rawUrl: _rawUrl, ...resource }) => resource),
);
expect(
reconcileCapturedWebScript(
{ ...script, rawUrl: app.rawUrl },
rawResources,
resources,
),
).toEqual({
status: "exact",
resource_key: resources.find(({ url }) => url === script.url)
?.resource_key,
});
}
});
});