test(javascript): consolidate semantic graph coverage

This commit is contained in:
morluto committed 2026-11-17 21:02:58 -05:00
1 parent e2e3881c0e
commit c77d4261a1
17 files changed
+684 -1098

No files matched your search

@@ -1,6 +1,5 @@
import { expect, it } from "vitest";
import { completeApplicationCoverage } from "../../domain/javascript/javascriptApplicationEvidenceSchemas.js";
import { createJavaScriptApplicationNode } from "../../domain/javascript/javascriptApplicationGraph.js";
import { JavaScriptArtifactGraphAccumulator } from "./JavaScriptArtifactGraphAccumulator.js";
import { artifactObservationEvidence } from "./JavaScriptArtifactGraphEvidence.js";
@@ -25,73 +24,45 @@ const nodeInput = (value: string, sha256 = "a".repeat(64)) => ({
],
});
it("retains live references, exact deduplication and canonical output across later additions", () => {
it("updates held nodes and deduplicates observations across finalization", () => {
const accumulator = new JavaScriptArtifactGraphAccumulator();
const inputs = ["雪😀", "alpha", "beta"].map((value) => nodeInput(value));
const firstInput = inputs[0];
if (firstInput === undefined) throw new Error("Missing first input");
const node = accumulator.addNode(firstInput);
const observations = node.observations;
const firstObservation = observations[0];
expect(accumulator.addNode(firstInput)).toBe(node);
expect(node.observations).toBe(observations);
expect(observations).toHaveLength(1);
expect(observations[0]).not.toBe(firstObservation);
for (const input of inputs.slice(1))
expect(accumulator.addNode(input)).toBe(node);
const secondNode = accumulator.addNode(nodeInput("other", "b".repeat(64)));
const firstSnapshot = accumulator.nodes();
const expectedNode = createJavaScriptApplicationNode({
...firstInput,
observations: inputs.flatMap((input) => input.observations),
});
expect(firstSnapshot).toEqual([expectedNode, secondNode]);
expect(firstSnapshot[0]).toBe(node);
expect(node.observations).toBe(observations);
const finalizedObservations = [...observations];
expect(accumulator.nodes()).not.toBe(firstSnapshot);
expect(accumulator.nodes()).toEqual(firstSnapshot);
for (const [index, observation] of finalizedObservations.entries())
expect(node.observations[index]).toBe(observation);
const later = nodeInput("later");
expect(accumulator.addNode(later)).toBe(node);
// Updating a duplicate after final sorting must use its new array index.
expect(accumulator.addNode(firstInput)).toBe(node);
expect(accumulator.nodes()).toEqual([
createJavaScriptApplicationNode({
...firstInput,
observations: [...inputs, later].flatMap((input) => input.observations),
}),
secondNode,
]);
expect(node.observations).toBe(observations);
});
it("preserves first-input duplicates and retains the last occurrence when later merged", () => {
const accumulator = new JavaScriptArtifactGraphAccumulator();
const first = nodeInput("same");
const distinct = nodeInput("distinct");
const node = accumulator.addNode({
const first = nodeInput("雪😀");
const held = accumulator.addNode({
...first,
observations: [...first.observations, ...first.observations],
});
const observations = node.observations;
const lastInitial = observations[1];
expect(accumulator.nodes()[0]?.observations).toHaveLength(2);
expect(accumulator.addNode(distinct)).toBe(node);
expect(accumulator.nodes()).toEqual([
createJavaScriptApplicationNode({
...first,
observations: [...first.observations, ...distinct.observations],
}),
]);
expect(node.observations).toBe(observations);
expect(observations).toContain(lastInitial);
// A repeated observation inside an incoming batch also collapses to one.
const other = accumulator.addNode(nodeInput("other", "b".repeat(64)));
const alpha = nodeInput("alpha");
accumulator.addNode({
...distinct,
observations: [...distinct.observations, ...distinct.observations],
...alpha,
observations: [...alpha.observations, ...alpha.observations],
});
expect(accumulator.nodes()[0]?.observations).toHaveLength(2);
accumulator.addNode(nodeInput("beta"));
const labels = () => held.observations.map(({ label }) => label).sort();
const finalized = accumulator.nodes();
expect(labels()).toEqual(["alpha", "beta", "雪😀"]);
expect(finalized.map(({ node_id }) => node_id).toSorted()).toEqual(
[held.node_id, other.node_id].toSorted(),
);
const identifiers = held.observations.map(
({ observation_id }) => observation_id,
);
expect(identifiers).toEqual(identifiers.toSorted());
accumulator.addNode(nodeInput("later"));
accumulator.addNode(first);
expect(labels()).toEqual(["alpha", "beta", "later", "雪😀"]);
const published = accumulator.nodes();
expect(
published
.find(({ node_id }) => node_id === held.node_id)
?.observations.map(({ label }) => label)
.sort(),
).toEqual(["alpha", "beta", "later", "雪😀"]);
expect(
published
.find(({ node_id }) => node_id === other.node_id)
?.observations.map(({ label }) => label),
).toEqual(["other"]);
});
@@ -186,48 +186,36 @@ it.each([
},
);
it("keeps assignments in computed methods' parameter defaults in the method", () => {
it("keeps assignments with the callable that evaluates them inside computed methods", () => {
const graph = graphForJavaScript(`
const accel = 0.001; let speed = 6;
const obj = { ["tick"](value = (speed = accel)) { return speed; } };
const accel = 0.001; let parameterSpeed = 6; let callbackSpeed = 6; let callback;
const withDefault = { ["tick"](value = (parameterSpeed = accel)) { return parameterSpeed; } };
const withKeyCallback = { [(() => { callbackSpeed = accel; return "tick"; })()]() {} };
const withDeferredCallback = { [(callback = () => accel)]() {} };
`);
const nodes = new Map(graph.nodes.map((node) => [node.node_id, node]));
const assignment = graph.relations.find(
(edge) => edge.properties.assignment_operator === "=",
);
expect(assignment).toBeDefined();
const source = nodes.get(assignment!.source_node_id);
const target = nodes.get(assignment!.target_node_id);
expect(source?.function_node_id).toBeTypeOf("string");
expect(source?.function_node_id).toBe(target?.function_node_id);
});
it("does not treat a callback body nested in a computed key as a key-time assignment input", () => {
const graph = graphForJavaScript(`
const accel = 0.001; let callback;
const obj = { [(callback = () => accel)]() {} };
`);
expect(
graph.relations.filter(
(edge) => edge.properties.assignment_operator !== undefined,
),
).toEqual([]);
});
it("retains an assignment owned by a callback inside a computed key", () => {
const graph = graphForJavaScript(`
const accel = 0.001; let speed = 6;
const obj = { [(() => { speed = accel; return "tick"; })()]() {} };
`);
const nodes = new Map(graph.nodes.map((node) => [node.node_id, node]));
const assignment = graph.relations.find(
(edge) => edge.properties.assignment_operator === "=",
);
expect(assignment).toBeDefined();
const source = nodes.get(assignment!.source_node_id);
const target = nodes.get(assignment!.target_node_id);
expect(source?.label).toBe("accel");
expect(target?.label).toBe("speed");
expect(source?.function_node_id).toBeTypeOf("string");
expect(source?.function_node_id).toBe(target?.function_node_id);
const assignments = graph.relations
.filter(({ properties }) => properties.assignment_operator === "=")
.map(({ source_node_id, target_node_id }) => ({
source: nodes.get(source_node_id),
target: nodes.get(target_node_id),
}));
expect(assignments.map(({ target }) => target?.label).sort()).toEqual([
"callbackSpeed",
"parameterSpeed",
]);
for (const { source, target } of assignments) {
expect(source?.label).toBe("accel");
const owner = source?.function_node_id;
if (owner == null) throw new Error("Expected an assignment owner");
expect(target?.function_node_id).toBe(owner);
expect(nodes.get(owner)).toMatchObject({
kind: "function",
identity: {
source_range: {
start: { line: target?.label === "parameterSpeed" ? 3 : 4 },
},
},
});
}
});
@@ -13,11 +13,6 @@ import {
createJavaScriptSemanticGraphProjection,
projectJavaScriptSemanticFileSteps,
} from "./JavaScriptSemanticGraphBuilder.js";
import {
addSemanticGraphNode,
constructSemanticGraphNode,
createSemanticGraphProjectionState,
} from "./JavaScriptSemanticGraphConstruction.js";
import type { JavaScriptArtifactFile } from "../../domain/javascript/javascriptArtifactFiles.js";
import { queryJavaScriptSemanticGraph } from "../../domain/javascript/javascriptSemanticQuery.js";
import {
@@ -25,7 +20,6 @@ import {
analyzeParsedJavaScriptSemantics,
} from "../../domain/javascript/javascriptSemanticAnalysis.js";
import { parseJavaScriptSource } from "../../domain/javascript/javascriptSourceParser.js";
import { semanticCoverageResourceLimits } from "../../domain/javascript/javascriptSemanticCoverage.js";
import { getterExpansionSource } from "../../../tests/fixtures/javascriptGetterExpansion.js";
const SHA256 = "a".repeat(64);
@@ -56,6 +50,7 @@ it("retains direct call literals and resolves literal queries to their argument"
direction: "forward-influence",
}),
);
expect(trace.seed_node_ids).toHaveLength(1);
expect(
trace.nodes.find((node) => node.node_id === trace.seed_node_ids[0])?.label,
).toBe("argument 0");
@@ -64,9 +59,7 @@ it("retains direct call literals and resolves literal queries to their argument"
it("reports the primitive byte bound when a direct argument is too large", () => {
const source = `rpc(${JSON.stringify("x".repeat(175_000))});`;
const ir = analyzeJavaScriptSemantics(source);
expect(ir.coverage.resourceLimits).toContain("primitive-bytes");
const graph = graphFor(source, ir);
const graph = graphFor(source);
const call = graph.nodes.find(({ kind }) => kind === "call-site");
expect(call?.properties.arguments).toBeUndefined();
expect(graph.coverage.status).not.toBe("complete");
@@ -267,16 +260,6 @@ it.each([
);
});
it("continues to project an ordinary member access as a property read", () => {
const graph = graphFor(`
const source = { count: 1 };
const value = source.count;
`);
expect(graph.relations).toContainEqual(
expect.objectContaining({ relation: "reads-property" }),
);
});
it("keeps a directly returned or passed property in backward provenance", () => {
const source = `
const settings = { index: "products" };
@@ -305,6 +288,9 @@ it("keeps a directly returned or passed property in backward provenance", () =>
const concatenated = added();
`;
const graph = graphFor(source);
expect(graph.relations).toContainEqual(
expect.objectContaining({ relation: "reads-property" }),
);
const provenance = (binding: string, candidates: boolean) => {
const node = graph.nodes.find(
(item) => item.kind === "binding" && item.label === binding,
@@ -324,99 +310,83 @@ it("keeps a directly returned or passed property in backward provenance", () =>
};
for (const binding of ["a", "b", "direct", "c", "d", "e", "g", "local"]) {
expect(provenance(binding, false), binding).toBe(true);
expect(provenance(binding, true), `${binding} candidates`).toBe(true);
}
expect(provenance("concatenated", false)).toBe(false);
expect(provenance("concatenated", true)).toBe(false);
});
it("keeps dynamic calls explicit and returns complete deterministic results", () => {
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,
it("retains the unresolved call frontier at the computed call site", () => {
const graph = graphFor(
[
"const handlers = { ready() { return 1; } };",
"const key = process.argv[2];",
"handlers[key]();",
].join("\n"),
);
const seedNodeId = graph.relations.find(
({ relation }) => relation === "defines",
)?.source_node_id;
if (seedNodeId === undefined) throw new Error("Expected a definition seed");
const first = queryJavaScriptSemanticGraph(
graph,
javaScriptSemanticQueryInputSchema.parse({
seed: { kind: "semantic-node", node_id: seedNodeId },
direction: "forward-influence",
include_ambiguous_dynamic_edges: true,
}),
);
const repeated = queryJavaScriptSemanticGraph(
graph,
javaScriptSemanticQueryInputSchema.parse({
seed: { kind: "semantic-node", node_id: seedNodeId },
direction: "forward-influence",
include_ambiguous_dynamic_edges: true,
}),
);
expect(repeated).toEqual(first);
});
it("preserves primitive candidate budget unknowns in semantic graph coverage", () => {
const source = `const answer = ${primitiveCandidateExpansionExpression()};`;
const ir = analyzeJavaScriptSemantics(source);
const graph = graphFor(source, ir);
expect(ir.coverage).toMatchObject({
status: "partial",
resourceLimits: ["primitive-candidates"],
});
const module = graph.nodes.find(({ kind }) => kind === "module");
if (module === undefined) throw new Error("Expected the containing module");
expect(
graph.unknowns.filter(({ reason }) => reason === "resource-limit"),
).toEqual([
expect.objectContaining({
family: "data-flow",
reason: "resource-limit",
detail: expect.stringMatching(/primitive candidate budget exceeded/i),
}),
graph.unknowns.filter(({ reason }) => reason === "dynamic-call"),
).toMatchObject([
{
node_id: module.node_id,
family: "call-flow",
relation_kinds: ["calls"],
candidate_node_ids: [],
evidence: {
location: {
available: true,
value: {
kind: "source-range",
source: "app.js",
start: { line: 3, column: 0 },
},
},
},
},
]);
});
it("preserves derived string-byte limit reasons in semantic graph unknowns", () => {
const source = primitiveByteExpansionSource();
const ir = analyzeJavaScriptSemantics(source);
const graph = graphFor(source, ir);
expect(semanticCoverageResourceLimits(ir.coverage)).toContain(
"primitive-bytes",
const graph = graphFor(primitiveByteExpansionSource());
const answer = graph.nodes.find(
({ kind, label }) => kind === "binding" && label === "answer",
);
if (answer === undefined)
throw new Error("Expected the derived value binding");
expect(graph.unknowns).toContainEqual(
expect.objectContaining({
node_id: answer.node_id,
family: "data-flow",
relation_kinds: ["defines"],
reason: "resource-limit",
detail: expect.stringMatching(/primitive string-byte budget exceeded/i),
}),
);
});
it("retains resource-limit reasons at nested object property slots", () => {
it("retains primitive candidate exhaustion at the nested property slot", () => {
const source = `const answer = { nested: { value: ${primitiveCandidateExpansionExpression()} } };`;
const ir = analyzeJavaScriptSemantics(source);
const graph = graphFor(source, ir);
expect(semanticCoverageResourceLimits(ir.coverage)).toEqual([
"primitive-candidates",
]);
expect(graph.unknowns).toContainEqual(
expect.objectContaining({
const graph = graphFor(source);
const slot = graph.nodes.find(
({ kind, properties }) =>
kind === "property-slot" &&
properties.property_pointer === "/nested/value",
);
if (slot === undefined) throw new Error("Expected the nested property slot");
expect(
graph.unknowns.filter(({ reason }) => reason === "resource-limit"),
).toMatchObject([
{
node_id: slot.node_id,
family: "data-flow",
relation_kinds: ["defines"],
reason: "resource-limit",
detail: expect.stringMatching(
/Unknown value at property:\/nested\/value/u,
/primitive candidate budget exceeded.*Unknown value at property:\/nested\/value/iu,
),
}),
);
},
]);
});
it("preserves deep expression resource reasons through graph projection", () => {
@@ -432,12 +402,8 @@ it("preserves deep expression resource reasons through graph projection", () =>
for (let index = 0; index < 5_000; index += 1)
expression = t.unaryExpression("!", expression, true);
declarator.init = expression;
const ir = analyzeParsedJavaScriptSemantics(parsed);
const graph = graphFor(source, ir);
const graph = graphFor(source, analyzeParsedJavaScriptSemantics(parsed));
expect(semanticCoverageResourceLimits(ir.coverage)).toEqual([
"expression-depth",
]);
expect(
graph.unknowns.filter(({ reason }) => reason === "resource-limit"),
).toEqual([
@@ -769,31 +735,6 @@ it("keeps uncertain parser results as candidates and ignores shadowed coercions"
).toBe(false);
});
const semanticNodeFor = (roleKey: string) => {
const file: JavaScriptArtifactFile = {
path: "budget.js",
container_sha256: SHA256,
sha256: SHA256,
bytes: 0,
inventory_artifact_id: `art_${SHA256}`,
kind: "javascript",
unpacked: false,
text: { included: true, value: "" },
};
const state = createSemanticGraphProjectionState();
return constructSemanticGraphNode(
file,
{
kind: "expression",
roleKey,
location: null,
label: roleKey,
functionNodeId: null,
},
state,
);
};
it("preserves getter expansion limits in semantic graph coverage", () => {
const source = getterExpansionSource();
const graph = graphFor(source, analyzeJavaScriptSemantics(source));
@@ -1126,53 +1067,34 @@ it("attributes an adopted file to the ceiling that bounded its offer", () => {
expect(limitation).not.toContain("max_semantic_nodes is 10");
});
it("leaves a small application complete and untruncated", () => {
const graph = graphFor("const answer = 40 + 2;");
expect(graph.coverage.truncated).toBe(false);
expect(graph.coverage.omitted_nodes).toBe(0);
expect(graph.coverage.omitted_relations).toBe(0);
expect(graph.coverage.limits).toEqual([]);
});
it("does not mark a file truncated when it exactly fills its budget", () => {
// Each unbound reference projects one expression, plus the module root.
const graph = graphFor(
"external;\n".repeat(
JAVASCRIPT_ANALYSIS_RESOURCE_DEFAULTS.semanticNodesPerFile - 1,
),
);
expect(graph.nodes).toHaveLength(
JAVASCRIPT_ANALYSIS_RESOURCE_DEFAULTS.semanticNodesPerFile,
);
expect(graph.coverage).toMatchObject({
it("reports truncation only when a file exceeds its exact node budget", () => {
const sources = [{ path: "exact.js", text: "first;\nsecond;\nthird;" }];
const exact = finishSources({ totalNodes: 10, fileNodes: 4 }, sources);
expect(exact.nodes).toHaveLength(4);
expect(exact.coverage).toMatchObject({
status: "unknown",
truncated: false,
omitted_nodes: 0,
omitted_relations: 0,
limits: [],
});
});
it("only records node loss when the budget rejects a new identity", () => {
// The truncation signal must record blocked node creation, not a zero
// remaining budget: a file using exactly its share drops nothing.
const state = createSemanticGraphProjectionState();
state.fileNodeBudget = 2;
state.fileNodesDropped = false;
const first = addSemanticGraphNode(state, semanticNodeFor("first"));
const second = addSemanticGraphNode(state, semanticNodeFor("second"));
expect(first).not.toBeNull();
expect(second).not.toBeNull();
expect(state.fileNodeBudget).toBe(0);
expect(state.fileNodesDropped).toBe(false);
expect(addSemanticGraphNode(state, semanticNodeFor("first"))).toEqual(first);
expect(state.nodes.size).toBe(2);
expect(state.fileNodeBudget).toBe(0);
expect(state.fileNodesDropped).toBe(false);
const blocked = addSemanticGraphNode(state, semanticNodeFor("third"));
expect(blocked).toBeNull();
expect(state.fileNodesDropped).toBe(true);
const exceeded = finishSources({ totalNodes: 10, fileNodes: 3 }, sources);
const dropped = exact.nodes.filter(
({ identity }) => identity.source_range?.start.line === 3,
);
expect(dropped).toHaveLength(1);
expect(exceeded.nodes.map(({ node_id }) => node_id)).toEqual(
exact.nodes
.filter((node) => node !== dropped[0])
.map(({ node_id }) => node_id),
);
expect(exceeded.coverage).toMatchObject({
status: "partial",
truncated: true,
});
expect(exceeded.limitations.join("\n")).toContain(
"max_semantic_nodes_per_file is 3",
);
});
it("keeps full static property identities distinct through backward provenance", () => {
@@ -196,7 +196,7 @@ export const retainSemanticGraphNode = (
};
/** Retain one canonical semantic node. */
export const addSemanticGraphNode = (
const addSemanticGraphNode = (
state: SemanticGraphProjectionState,
node: JavaScriptSemanticGraphNode,
knownLookupKey?: string,
@@ -1,8 +1,8 @@
import { expect, it } from "vitest";
import { graphForJavaScript } from "../../../tests/fixtures/javascriptSemanticGraph.js";
it.each(
[
it("links declared and assigned destructuring bindings to their exact source slots", () => {
const cases = [
{ pattern: "{ a: selected }", source: "{ a: 1 }", path: ["a"] },
{ pattern: "[selected]", source: "[1]", path: ["0"] },
{
@@ -16,33 +16,41 @@ it.each(
path: ["a", "b"],
},
{ pattern: "[[selected] = []]", source: "[[1]]", path: ["0", "0"] },
].flatMap((pattern) =>
[false, true].map((assignment) => ({ ...pattern, assignment })),
),
)(
"retains source-property flow for $pattern, assignment=$assignment",
({ pattern, source, path, assignment }) => {
const graph = graphForJavaScript(`
const source = ${source};
${assignment ? `let selected; (${pattern} = source);` : `const ${pattern} = source;`}
`);
const target = graph.nodes.find(
(node) => node.kind === "binding" && node.label === "selected",
);
expect(target).toBeDefined();
const relations = graph.relations.filter(
(relation) =>
relation.relation === "destructures" &&
relation.target_node_id === target?.node_id,
);
expect(relations).toHaveLength(1);
expect(relations[0]?.resolution).toBe("resolved");
const slot = graph.nodes.find(
(node) => node.node_id === relations[0]?.source_node_id,
);
expect(slot?.properties.property_path).toEqual(path);
},
);
];
const graph = graphForJavaScript(
cases
.map(({ pattern, source }, index) =>
[
`const source${index} = ${source};`,
`const ${pattern.replace("selected", `declared${index}`)} = source${index};`,
`let assigned${index};`,
`(${pattern.replace("selected", `assigned${index}`)} = source${index});`,
].join("\n"),
)
.join("\n"),
);
const nodes = new Map(graph.nodes.map((node) => [node.node_id, node]));
expect(
graph.relations
.filter(({ relation }) => relation === "destructures")
.map(({ source_node_id, target_node_id, resolution }) => ({
target: nodes.get(target_node_id)?.label,
path: nodes.get(source_node_id)?.properties.property_path,
resolution,
}))
.sort((left, right) =>
String(left.target).localeCompare(String(right.target)),
),
).toEqual(
["assigned", "declared"].flatMap((form) =>
cases.map(({ path }, index) => ({
target: `${form}${index}`,
path,
resolution: "resolved",
})),
),
);
});
it.each(["{}", "unknownSource"])(
"keeps nested default source flow conservative for %s",
@@ -2,7 +2,10 @@ import { expect, it } from "vitest";
import { analyzeJavaScriptStaticSource } from "../../../tests/fixtures/javascriptStaticAnalysis.js";
import { analyzeJavaScriptSemantics } from "../../domain/javascript/javascriptSemanticAnalysis.js";
import type { JavaScriptArtifactFile } from "../../domain/javascript/javascriptArtifactFiles.js";
import { projectJavaScriptSemanticFileSteps } from "./JavaScriptSemanticGraphBuilder.js";
import {
createJavaScriptSemanticGraphProjection,
projectJavaScriptSemanticFileSteps,
} from "./JavaScriptSemanticGraphBuilder.js";
const source = `${Array.from({ length: 40 }, (_, i) => `function library${String(i)}(){return ${String(i)}}`).join("\n")}
const e=require("electron");
@@ -20,53 +23,53 @@ const file: JavaScriptArtifactFile = {
};
const facts = analyzeJavaScriptStaticSource(source);
const ir = analyzeJavaScriptSemantics(source);
const project = (budget: number) => {
const steps = projectJavaScriptSemanticFileSteps(
file,
ir,
{ nodes: budget, unknowns: budget },
facts.electron.call_paths,
);
let result = steps.next();
while (!result.done) result = steps.next();
return result.value;
};
it("retains Electron boundary evidence until the node budget cuts the path", () => {
for (const budget of [3, 20]) {
const projection = createJavaScriptSemanticGraphProjection({
totalNodes: budget,
fileNodes: budget,
});
const steps = projectJavaScriptSemanticFileSteps(
file,
ir,
projection.remainingFileCapacity(),
facts.electron.call_paths,
);
let result = steps.next();
while (!result.done) result = steps.next();
projection.adoptFileProjection(result.value);
const graph = projection.finish(file.container_sha256, {
graph_id: `jag_${"c".repeat(64)}`,
nodes: [],
});
it("retains Electron calls before library definitions consume the node budget", () => {
const result = project(20);
expect(result.nodes).toHaveLength(20);
expect(result.nodesTruncated).toBe(true);
const terminal = result.nodes.find(
(node) => node.label === "ipc-event.sender.copy",
);
expect(terminal).toBeDefined();
expect(
result.relations.some(
(r) =>
r.target_node_id === terminal?.node_id && r.resolution === "candidate",
),
).toBe(true);
expect(
result.nodes.some(
(node) =>
node.properties.entry === "test:copy" &&
Array.isArray(node.properties.conditions) &&
node.properties.conditions.length === 1,
),
).toBe(true);
});
it("reports truncation and keeps referential integrity even within a boundary path", () => {
const result = project(3);
expect(result.nodes).toHaveLength(3);
expect(result.nodesTruncated).toBe(true);
expect(
result.nodes.some((node) => node.label === "ipc-event.sender.copy"),
).toBe(false);
const retained = new Set(result.nodes.map((node) => node.node_id));
expect(
result.relations.every(
(r) => retained.has(r.source_node_id) && retained.has(r.target_node_id),
),
).toBe(true);
expect(graph.nodes).toHaveLength(budget);
expect(graph.coverage).toMatchObject({
status: "partial",
truncated: true,
});
const terminal = graph.nodes.find(
({ label }) => label === "ipc-event.sender.copy",
);
if (budget === 3) {
expect(terminal).toBeUndefined();
continue;
}
if (terminal === undefined)
throw new Error("Expected the Electron terminal");
expect(graph.relations).toContainEqual(
expect.objectContaining({
target_node_id: terminal.node_id,
resolution: "candidate",
}),
);
expect(graph.nodes).toContainEqual(
expect.objectContaining({
properties: expect.objectContaining({
entry: "test:copy",
conditions: [expect.anything()],
}),
}),
);
}
});
@@ -201,23 +201,6 @@ it("keeps sequence side effects unknown instead of attributing earlier values di
).toBe(true);
});
it("seeds a direct argument at its occurrence and reaches the call", () => {
const graph = graphForJavaScript('consume("only-direct");');
const result = queryJavaScriptSemanticGraph(
graph,
javaScriptSemanticQueryInputSchema.parse({
seed: { kind: "literal", value: "only-direct" },
direction: "forward-influence",
}),
);
expect(result.summary.total_seed_matches).toBe(1);
expect(
result.nodes.find((node) => node.node_id === result.seed_node_ids[0])
?.label,
).toBe("argument 0");
expect(result.nodes.some((node) => node.kind === "call-site")).toBe(true);
});
it("keeps older call-site literal evidence searchable when argument literals are absent", () => {
const graph = graphForJavaScript('consume("only-direct");');
const legacy = {
@@ -9,25 +9,21 @@ import { resolveJavaScriptSemanticEvidence } from "../../../tests/support/javasc
const SHA256 = "a".repeat(64);
const GRAPH_ID = `jag_${"b".repeat(64)}`;
it("projects literal events and exact timer cancellation", () => {
it("keeps literal event links and dynamic event uncertainty", () => {
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(
@@ -45,9 +41,6 @@ it("projects literal events and exact timer cancellation", () => {
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", () => {
@@ -65,32 +58,41 @@ it("projects child-process creation, I/O, listeners, and signals", () => {
}
`);
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);
const child = graph.nodes.find(({ kind }) => kind === "child-process");
if (child === undefined) throw new Error("Expected the spawned child");
expect(child.properties).toMatchObject({
method: "spawn",
command: null,
argv_count: 2,
environment_supplied: true,
stdio_mode: "pipe",
});
expect(
graph.nodes.find(
({ kind, properties }) =>
kind === "child-process" &&
properties.method === "spawn" &&
properties.command === null,
),
).toBeDefined();
graph.relations
.filter(({ target_node_id }) => target_node_id === child.node_id)
.map(({ relation }) => relation),
).toEqual(
expect.arrayContaining([
"forwards-signal",
"spawns",
"supplies-argv",
"supplies-env",
]),
);
expect(
graph.unknowns.some(
({ family, detail }) =>
family === "child-process" &&
detail.includes("command remains unresolved"),
),
).toBe(true);
graph.relations
.filter(({ source_node_id }) => source_node_id === child.node_id)
.map(({ relation }) => relation),
).toEqual(
expect.arrayContaining(["connects-stdio", "listens-error", "listens-exit"]),
);
expect(graph.unknowns).toContainEqual(
expect.objectContaining({
node_id: child.node_id,
family: "child-process",
detail: expect.stringContaining("command remains unresolved"),
}),
);
expect(
graph.coverage.families.find(({ family }) => family === "child-process"),
).toMatchObject({ status: "partial" });
@@ -231,18 +233,48 @@ it("projects built-in resource acquisition and release", () => {
).toMatchObject({ status: "partial" });
});
it.each(["+= 1", "++"])(
"projects both property dependencies for %s",
(operator) => {
const graph = graphFor(`
const source = { count: 1 };
source.count ${operator};
`);
const relations = graph.relations.map(({ relation }) => relation);
expect(relations).toContain("reads-property");
expect(relations).toContain("writes-property");
},
);
it("links the read and write of each update to the same property slot", () => {
const graph = graphFor(`
const source = { count: 1, total: 2 };
source.count += 1;
source.total++;
`);
for (const path of ["count", "total"]) {
const slot = graph.nodes.find(
({ kind, properties }) =>
kind === "property-slot" && properties.property_pointer === `/${path}`,
);
if (slot === undefined) throw new Error(`Expected the ${path} slot`);
const updates = graph.nodes.filter(
({ properties }) =>
Array.isArray(properties.property_path) &&
properties.property_path[0] === path,
);
const read = updates.find(
({ properties }) => properties.operation_kind === "read",
);
const write = updates.find(
({ properties }) => properties.operation_kind === "write",
);
if (read === undefined || write === undefined)
throw new Error(`Expected both operations for ${path}`);
expect(graph.relations).toEqual(
expect.arrayContaining([
expect.objectContaining({
relation: "reads-property",
source_node_id: slot.node_id,
target_node_id: read.node_id,
}),
expect.objectContaining({
relation: "writes-property",
source_node_id: write.node_id,
target_node_id: slot.node_id,
}),
]),
);
}
});
it("does not project a literal property slot for dynamic destructuring", () => {
const graph = graphFor(`
const source = { token: "TOKEN" };
@@ -1,105 +1,48 @@
import { expect, it } from "vitest";
import { graphForJavaScript as graphFor } from "../../../tests/fixtures/javascriptSemanticGraph.js";
import { analyzeJavaScriptSemantics } from "../../domain/javascript/javascriptSemanticAnalysis.js";
import { topLevelBinding } from "../../domain/javascript/javascriptSemanticAnalysis.fixture.js";
import { graphForJavaScript } from "../../../tests/fixtures/javascriptSemanticGraph.js";
const dynamicScopeUnknowns = (source: string) =>
graphFor(source).unknowns.filter(({ reason }) => reason === "dynamic-scope");
it("exposes direct eval and with as dynamic-scope unknowns in the public graph", () => {
const unknowns = dynamicScopeUnknowns(`
function inspect(host, source) {
with (host) { consume(target); }
eval(source);
}
`);
it("records dynamic scope only at with and unshadowed direct eval", () => {
const graph = graphForJavaScript(
[
"function inspect(host, source) {",
" with (host) { consume(target); }",
" eval(source);",
"}",
"function shadowed(eval, source) { eval(source); }",
"function optional(source) { eval?.(source); }",
"function indirect(source) { (0, eval)(source); }",
].join("\n"),
);
const inspect = graph.nodes.find(
({ label, kind }) => kind === "function" && label === "inspect",
);
if (inspect === undefined)
throw new Error("Expected the containing function");
const unknowns = graph.unknowns.filter(
({ reason }) => reason === "dynamic-scope",
);
expect(unknowns).toHaveLength(2);
expect(unknowns.map(({ detail }) => detail).join("\n")).toEqual(
expect.stringContaining("with"),
);
expect(unknowns.map(({ detail }) => detail).join("\n")).toEqual(
expect.stringContaining("eval"),
);
});
it("does not mark shadowed, optional, or indirect eval as dynamic scope", () => {
const unknowns = dynamicScopeUnknowns(`
function shadowed(eval, source) { eval(source); }
function optional(source) { eval?.(source); }
function indirect(source) { (0, eval)(source); }
`);
expect(unknowns).toEqual([]);
});
it("keeps switch discriminants outside the shared case lexical scope", () => {
const ir = analyzeJavaScriptSemantics(`
const selected = choose();
switch (selected) {
case 1: let selected = 1; let local = 1; break;
case 2: local = 2; break;
}
`);
const selectedBinding = topLevelBinding(ir, "selected");
const localBindings = ir.bindings.filter(({ name }) => name === "local");
expect(ir.references.find(({ name }) => name === "selected")?.bindingId).toBe(
selectedBinding.bindingId,
);
expect(localBindings).toHaveLength(1);
expect(localBindings[0]?.scopeId).not.toBe(selectedBinding?.scopeId);
expect(
ir.references.filter(
({ name, role }) => name === "selected" && role === "read",
),
).toHaveLength(1);
expect(
ir.references.filter(
({ name, role }) => name === "local" && role === "write",
),
).toHaveLength(1);
});
it("leaves with-object resolution intact and marks only body name resolution unknown", () => {
const ir = analyzeJavaScriptSemantics(`
const host = getHost();
const outer = 3;
function inspect() {
with (host) {
const local = 1;
consume(local, outer);
}
}
`);
const host = topLevelBinding(ir, "host");
const hostRead = ir.references.find(
({ name, role }) => name === "host" && role === "read",
);
const outerRead = ir.references.find(
({ name, role }) => name === "outer" && role === "read",
);
const localRead = ir.references.find(
({ name, role }) => name === "local" && role === "read",
);
expect(hostRead?.bindingId).toBe(host.bindingId);
expect(hostRead?.resolution).toBe("resolved");
expect(outerRead?.resolution).toBe("unknown");
expect(localRead?.resolution).toBe("resolved");
expect(outerRead?.bindingId).toBeNull();
});
it("keeps var declarations in each static block from leaking to another block", () => {
const ir = analyzeJavaScriptSemantics(`
class Example {
static { var first = 1; }
static { var second = 2; consume(first); }
}
`);
const first = ir.bindings.filter(({ name }) => name === "first");
const second = ir.bindings.filter(({ name }) => name === "second");
expect(ir.references.find(({ name }) => name === "first")?.resolution).toBe(
"unbound",
);
expect(first).toHaveLength(1);
expect(second).toHaveLength(1);
expect(first[0]?.scopeId).not.toBe(second[0]?.scopeId);
for (const [statement, line] of [
["with", 2],
["eval", 3],
] as const) {
expect(unknowns).toContainEqual(
expect.objectContaining({
node_id: inspect.node_id,
family: "data-flow",
relation_kinds: ["reads", "writes"],
detail: expect.stringContaining(`\`${statement}\``),
evidence: expect.objectContaining({
location: expect.objectContaining({
available: true,
value: expect.objectContaining({
kind: "source-range",
start: { line, column: 2 },
}),
}),
}),
}),
);
}
});
@@ -64,26 +64,3 @@ it("keeps resolved property seeds on their slot without duplicating access occur
graph.nodes.find(({ node_id }) => node_id === trace.seed_node_ids[0])?.kind,
).toBe("property-slot");
});
it("queries an empty event name as an exact retained event identity", () => {
const graph = graphForJavaScript(
'const { EventEmitter } = require("node:events"); const bus = new EventEmitter(); bus.on("", function emptyListener() {}); bus.on("data", function dataListener() {});',
);
const trace = queryJavaScriptSemanticGraph(
graph,
javaScriptSemanticQueryInputSchema.parse({
seed: { kind: "event", name: "" },
direction: "forward-influence",
}),
);
expect(trace.seed_node_ids.length).toBeGreaterThan(0);
const seeds = trace.nodes.filter(({ node_id }) =>
trace.seed_node_ids.includes(node_id),
);
expect(seeds.map(({ node_id }) => node_id).sort()).toEqual(
[...trace.seed_node_ids].sort(),
);
expect(seeds.every(({ properties }) => properties.event_name === "")).toBe(
true,
);
});