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

@@ -6,10 +6,8 @@ import {
createJavaScriptApplicationGraph,
createJavaScriptApplicationNode,
mergeJavaScriptApplicationNodes,
javascriptApplicationGraphSchema,
parseJavaScriptApplicationGraph,
serializeJavaScriptApplicationGraph,
type JavaScriptApplicationGraph,
} from "./javascriptApplicationGraph.js";
import {
APPLICATION_GRAPH_DIGESTS,
@@ -35,6 +33,10 @@ it("merges observations by entity identity without changing source nodes", () =>
stability: "global-exact" as const,
strategy: "content-digest" as const,
};
expect(second.node_id).toBe(first.node_id);
expect(second.observations[0]?.observation_id).not.toBe(
first.observations[0]?.observation_id,
);
const merged = mergeJavaScriptApplicationNodes([
first,
{ ...second, identity: reversedIdentity },
@@ -77,13 +79,19 @@ it.each(["kind", "identity"] as const)(
},
);
const createLargeNativeExportGraph = (): JavaScriptApplicationGraph => {
const properties = Object.fromEntries(
Array.from({ length: 1_001 }, (_, index) => [
`${"export-property-"}${"k".repeat(120)}-${index}`,
"v".repeat(4_097),
]),
);
it("preserves deep and wide observation properties in a large native-export graph", () => {
let nested: unknown = "leaf";
for (let index = 0; index < 12; index += 1)
nested = { [`level-${index}`]: nested };
const largeKey = `export-property-${"k".repeat(120)}`;
const properties = {
...Object.fromEntries(
Array.from({ length: 1_000 }, (_, index) => [`symbol-${index}`, index]),
),
[largeKey]: "v".repeat(4_097),
nested,
};
const longLabel = "large export graph label ".repeat(300);
const nodes = Array.from({ length: 1_001 }, (_, index) => {
const path = `native/exports/${index}.symbol`;
return createJavaScriptApplicationNode({
@@ -96,7 +104,7 @@ const createLargeNativeExportGraph = (): JavaScriptApplicationGraph => {
},
observations: [
{
label: index === 0 ? "large export graph label ".repeat(300) : path,
label: index === 0 ? longLabel : path,
properties: index === 0 ? properties : {},
evidence: artifactEvidence(
APPLICATION_GRAPH_DIGESTS.nativeAddon,
@@ -107,69 +115,27 @@ const createLargeNativeExportGraph = (): JavaScriptApplicationGraph => {
],
});
});
const first = nodes[0];
if (first === undefined) throw new TypeError("Missing native export");
return createJavaScriptApplicationGraph({
const first = firstOf(nodes, "native export");
const graph = createJavaScriptApplicationGraph({
schema: "JavaScriptApplicationGraph",
root_node_ids: [first.node_id],
nodes,
edges: [],
coverage: {
status: "complete",
truncated: false,
omitted_count: 0,
limits: [],
},
coverage: completeCoverage,
limitations: [],
});
};
const loaded = parseJavaScriptApplicationGraph(
JSON.parse(serializeJavaScriptApplicationGraph(graph)),
);
it("accepts deeply nested canonical application properties", () => {
let nested: unknown = "leaf";
for (let index = 0; index < 12; index += 1)
nested = { [`level-${String(index)}`]: nested };
const node = createJavaScriptApplicationNode({
kind: "native-export",
identity: {
strategy: "canonical-path",
stability: "artifact-version",
artifact_sha256: APPLICATION_GRAPH_DIGESTS.nativeAddon,
path: "native/deep-export",
},
observations: [
{
label: "deep export",
properties: { nested },
evidence: artifactEvidence(
APPLICATION_GRAPH_DIGESTS.nativeAddon,
"native/deep-export",
"native-analysis-provider",
),
},
],
});
const graph = createJavaScriptApplicationGraph({
schema: "JavaScriptApplicationGraph",
root_node_ids: [node.node_id],
nodes: [node],
edges: [],
coverage: {
status: "complete",
truncated: false,
omitted_count: 0,
limits: [],
},
limitations: [],
});
expect(graph.nodes[0]?.observations[0]?.properties).toEqual({ nested });
expect(
parseJavaScriptApplicationGraph(
JSON.parse(serializeJavaScriptApplicationGraph(graph)),
),
).toEqual(graph);
expect(loaded.nodes.map(({ node_id }) => node_id).toSorted()).toEqual(
nodes.map(({ node_id }) => node_id).toSorted(),
);
const observation = loaded.nodes.find(
({ node_id }) => node_id === first.node_id,
)?.observations[0];
expect(observation?.label).toBe(longLabel);
expect(observation?.properties).toEqual(properties);
});
describe("JavaScript Application Graph: vocabulary", () => {
@@ -193,20 +159,6 @@ describe("JavaScript Application Graph: vocabulary", () => {
}),
).toEqual(graph);
});
it("keeps large native-export graphs and their complete properties", () => {
const graph = createLargeNativeExportGraph();
const largeExport = graph.nodes.find(({ observations }) =>
observations.some(({ label }) =>
label?.startsWith("large export graph label "),
),
);
expect(graph.nodes).toHaveLength(1_001);
expect(
Object.keys(largeExport?.observations[0]?.properties ?? {}),
).toHaveLength(1_001);
});
});
describe("JavaScript Application Graph: evidence authority", () => {
@@ -247,80 +199,51 @@ describe("JavaScript Application Graph: evidence authority", () => {
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", () => {
it("retains unknown observations but requires observed proof for an observation-scoped identity", () => {
const identity = {
strategy: "canonical-path" as const,
stability: "artifact-version" as const,
artifact_sha256: APPLICATION_GRAPH_DIGESTS.asar,
path: "dist/chunk.js",
strategy: "observation-fingerprint",
stability: "observation-only",
observation_sha256: "8".repeat(64),
scope: "synthetic static inventory",
};
const first = createJavaScriptApplicationNode({
kind: "javascript-chunk",
const unknown = {
label: null,
properties: { question: "runtime correspondence" },
evidence: unknownEvidence(),
};
const observed = {
label: "unclassified entity",
properties: {},
evidence: artifactEvidence(
APPLICATION_GRAPH_DIGESTS.asar,
"dist/module.js",
),
};
const node = createJavaScriptApplicationNode({
kind: "unknown",
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",
),
},
],
observations: [observed, unknown],
});
expect(first.node_id).toBe(second.node_id);
expect(first.observations[0]?.observation_id).not.toBe(
second.observations[0]?.observation_id,
expect(graphForNode(node).nodes[0]?.observations).toEqual(
expect.arrayContaining([
expect.objectContaining({
properties: { question: "runtime correspondence" },
evidence: expect.objectContaining({
state: "unknown",
authority: "unknown",
confidence: "unknown",
}),
}),
]),
);
const unsupported = createJavaScriptApplicationNode({
kind: "unknown",
identity,
observations: [unknown],
});
expect(() => graphForNode(unsupported)).toThrow(
/identity is not supported/u,
);
});
});
@@ -444,7 +367,7 @@ describe("JavaScript Application Graph: identity and evidence", () => {
});
describe("JavaScript Application Graph: source maps and observations", () => {
it("admits source-map and observation-scoped identities only with supporting observations", () => {
it("requires source-map observations to retain the declaration and map location", () => {
const sourceModule = createJavaScriptApplicationNode({
kind: "source-module",
identity: {
@@ -472,28 +395,7 @@ describe("JavaScript Application Graph: source maps and observations", () => {
},
],
});
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]);
const sourceObservation = firstOf(
sourceModule.observations,
"source observation",
@@ -604,9 +506,6 @@ describe("JavaScript Application Graph: source-map digest consistency", () => {
expect(() => graphForNode(sourceMapNode(null, null, true))).toThrow(
/Source-map observation/u,
);
expect(() =>
graphForNode(sourceMapNode("3".repeat(64), "3".repeat(64), undefined)),
).not.toThrow();
});
});
@@ -643,19 +542,8 @@ describe("JavaScript Application Graph: commitments and schemas", () => {
expect(() => parseJavaScriptApplicationGraph(staleEdge)).toThrow(
/Edge identifier/u,
);
});
it("creates exactly the graph the public schema accepts", () => {
const graph = buildSyntheticJavaScriptApplicationGraph();
expect(JSON.stringify(graph)).toBe(
JSON.stringify(
javascriptApplicationGraphSchema.parse(structuredClone(graph)),
),
);
const { graph_id: _graphId, ...semantic } = structuredClone(graph);
firstOf(semantic.edges, "edge").edge_id = `jag_edge_${"f".repeat(64)}`;
expect(() => createJavaScriptApplicationGraph(semantic)).toThrow(
const { graph_id: _graphId, ...staleInput } = staleEdge;
expect(() => createJavaScriptApplicationGraph(staleInput)).toThrow(
/Edge identifier/u,
);
});
@@ -978,7 +866,7 @@ describe("JavaScript Application Graph: identity strategy requirements", () => {
});
describe("JavaScript Application Graph: truncation claims", () => {
it("rejects false truncation claims and accepts large properties", () => {
it("rejects false truncation and incomplete-coverage claims", () => {
const truncated = artifactEvidence(
APPLICATION_GRAPH_DIGESTS.asar,
"dist/module.js",
@@ -1023,15 +911,5 @@ describe("JavaScript Application Graph: truncation claims", () => {
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,
).observations[0]?.properties,
).toEqual(properties);
});
});
@@ -765,19 +765,32 @@ describe("JavaScript semantic analysis: write references", () => {
});
describe("JavaScript semantic analysis: dynamic and case scopes", () => {
it("marks with and eval as unresolved dynamic scope instead of staying silent", () => {
it("resolves with receivers and local bindings while leaving outer reads unknown", () => {
const ir = analyzeJavaScriptSemantics(`
function load(source) {
with (host) { consume(target); }
eval("var injected = 1;");
const host = getHost();
const outer = 3;
function inspect() {
with (host) {
const local = 1;
consume(local, outer);
}
}
`);
const reasons = ir.frontiers
.filter(({ kind }) => kind === "dynamic-scope")
.map(({ reason }) => reason);
expect(reasons).toHaveLength(2);
expect(reasons.join("\n")).toContain("`with`");
expect(reasons.join("\n")).toContain("`eval`");
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("does not assign CommonJS exports to lexically shadowed module or exports", () => {
@@ -795,30 +808,53 @@ describe("JavaScript semantic analysis: dynamic and case scopes", () => {
).toEqual([]);
});
it("shares one lexical scope across switch cases and isolates static blocks", () => {
const switchIr = analyzeJavaScriptSemantics(`
const kind = select();
switch (kind) {
case "a": let shared = 1; break;
case "b": shared = 2; break;
it("resolves a switch discriminant outside the case scope and writes across cases", () => {
const ir = analyzeJavaScriptSemantics(`
const selected = choose();
switch (selected) {
case 1: let selected = 1; let shared = 1; break;
case 2: shared = 2; break;
}
`);
// One declaration, one binding — and it belongs to a scope of its own, so
// it cannot leak past the switch statement.
const shared = switchIr.bindings.filter(({ name }) => name === "shared");
const outer = topLevelBinding(ir, "selected");
const shared = bindingsNamed(ir, "shared");
expect(shared).toHaveLength(1);
expect(shared[0]?.scopeId).not.toBe(
topLevelBinding(switchIr, "kind").scopeId,
expect(shared[0]?.scopeId).not.toBe(outer.scopeId);
expect(
ir.references.filter(({ name }) => name === "selected"),
).toMatchObject([
{ role: "read", resolution: "resolved", bindingId: outer.bindingId },
]);
expect(ir.references.filter(({ name }) => name === "shared")).toMatchObject(
[
{
role: "write",
resolution: "resolved",
bindingId: shared[0]?.bindingId,
},
],
);
const classIr = analyzeJavaScriptSemantics(`
});
it("isolates let and var bindings between static blocks", () => {
const ir = analyzeJavaScriptSemantics(`
class Holder {
static { let isolated = 1; }
static { let isolated = 2; }
static { let isolated = 1; var first = 1; }
static { let isolated = 2; var second = 2; consume(first); }
}
`);
expect(
classIr.bindings.filter(({ name }) => name === "isolated"),
).toHaveLength(2);
const lexical = bindingsNamed(ir, "isolated");
const first = bindingsNamed(ir, "first");
const second = bindingsNamed(ir, "second");
expect(lexical).toHaveLength(2);
expect(lexical[0]?.scopeId).not.toBe(lexical[1]?.scopeId);
expect(first).toHaveLength(1);
expect(second).toHaveLength(1);
expect(first[0]?.scopeId).not.toBe(second[0]?.scopeId);
expect(ir.references.find(({ name }) => name === "first")).toMatchObject({
resolution: "unbound",
bindingId: null,
});
});
it("keeps function, class, and method identities separate from bindings", () => {
@@ -11,7 +11,6 @@ import { z } from "zod";
import { digestCanonicalValue } from "../canonicalDigest.js";
import type { JsonValue } from "../jsonValue.js";
import type { ApplicationGraphEvidence } from "./javascriptApplicationEvidenceSchemas.js";
import {
JAVASCRIPT_SEMANTIC_RELATION_FAMILIES,
JAVASCRIPT_SEMANTIC_RELATION_FAMILY,
@@ -38,7 +37,7 @@ import { queryJavaScriptSemanticGraph } from "./javascriptSemanticQuery.js";
const SHA = "a".repeat(64);
it.each(["unknown", "unavailable", "partial"] as const)(
it.each(["unknown", "partial"] as const)(
"rejects contradictory truncated %s graph coverage",
(status) => {
const input = semanticFixtureInput();
@@ -63,24 +62,6 @@ it.each(["unknown", "unavailable", "partial"] as const)(
},
);
it("accepts truncated partial coverage with unknown omission extents", () => {
const input = semanticFixtureInput();
expect(
createJavaScriptSemanticGraph({
...input,
coverage: {
...input.coverage,
status: "partial",
truncated: true,
omitted_nodes: null,
omitted_relations: null,
limits: [{ name: "nodes", value: 1, unit: "items" }],
},
limitations: ["Node ceiling left semantic omission extents unknown."],
}).coverage,
).toMatchObject({ status: "partial", truncated: true });
});
it("accepts omitted unknown occurrences as the reason for semantic truncation", () => {
const input = semanticFixtureInput();
const family = input.coverage.families[0]!.family;
@@ -106,6 +87,9 @@ it("accepts omitted unknown occurrences as the reason for semantic truncation",
truncated: true,
omitted_nodes: 0,
omitted_relations: 0,
omitted_unknown_occurrences: [
{ family, reason: "resource-limit", occurrences: 1 },
],
});
});
const node = (
@@ -475,17 +459,6 @@ it("counts candidate ownership cycles once and traverses them finitely", () => {
).toBe("found");
});
it("defines every required 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 = semanticFixtureGraph();
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 = semanticFixtureGraph();
expect(() =>
@@ -545,29 +518,7 @@ it("rejects stale identities, dangling endpoints, and incomplete coverage claims
it("rejects complete family coverage with an unlisted retained frontier", () => {
const input = semanticFixtureInput(true);
input.coverage = {
...input.coverage,
status: "complete",
truncated: false,
omitted_nodes: 0,
omitted_relations: 0,
families: input.coverage.families.map((family) =>
family.family === "call-flow"
? {
...family,
status: "complete",
omitted_relations: 0,
unknown_ids: [],
}
: family,
),
};
input.limitations = [];
expect(() => createJavaScriptSemanticGraph(input)).toThrow(
/Complete family coverage cannot omit or retain unknown facts/u,
);
const valid = createJavaScriptSemanticGraph(semanticFixtureInput(true));
const valid = createJavaScriptSemanticGraph(input);
const coverage = {
...valid.coverage,
status: "complete" as const,
@@ -594,45 +545,26 @@ it("rejects complete family coverage with an unlisted retained frontier", () =>
"JavaScript semantic graph",
)}`,
};
const parsed = javaScriptSemanticGraphSchema.safeParse(invalid);
expect(parsed.success).toBe(false);
const diagnostic =
"Complete family coverage cannot omit or retain unknown facts";
expect(() => createJavaScriptSemanticGraph(changed)).toThrow(diagnostic);
const parsed = javaScriptSemanticGraphSchema.safeParse(
JSON.parse(JSON.stringify(invalid)),
);
if (parsed.success) throw new Error("Expected inconsistent graph rejection");
expect(parsed.error.issues.map(({ message }) => message)).toContain(
"Complete family coverage cannot omit or retain unknown facts",
diagnostic,
);
expect(
javaScriptSemanticGraphSchema.safeParse(JSON.parse(JSON.stringify(invalid)))
.success,
).toBe(false);
});
it("validates evidence context ownership and references", () => {
const graph = semanticFixtureGraph();
const alteredContext = {
...graph,
evidence_contexts: graph.evidence_contexts.map((context, index) =>
index === 0
? { ...context, context_id: `jsrg_evidence_${"f".repeat(64)}` }
: context,
),
};
const alteredIssues = javaScriptSemanticGraphSchema.safeParse(alteredContext);
expect(alteredIssues.success).toBe(false);
if (alteredIssues.success) throw new Error("Expected invalid context digest");
expect(alteredIssues.error.issues.map(({ message }) => message)).toContain(
"Evidence context identifier is stale",
);
expect(alteredIssues.error.issues.map(({ message }) => message)).toContain(
"Evidence reference names an absent context",
);
const changedPayload = javaScriptSemanticGraphSchema.safeParse({
...graph,
evidence_contexts: graph.evidence_contexts.map((context, index) =>
index === 0 ? { ...context, authority: "user-assertion" } : context,
),
});
expect(changedPayload.success).toBe(false);
if (changedPayload.success)
throw new Error("Expected changed context payload rejection");
expect(changedPayload.error.issues.map(({ message }) => message)).toContain(
@@ -654,7 +586,6 @@ it("validates evidence context ownership and references", () => {
(left, right) => left.context_id.localeCompare(right.context_id),
),
});
expect(orphanIssues.success).toBe(false);
if (orphanIssues.success)
throw new Error("Expected orphan context rejection");
expect(orphanIssues.error.issues.map(({ message }) => message)).toContain(
@@ -683,7 +614,6 @@ it("validates evidence context ownership and references", () => {
...facts.slice(1),
],
});
expect(dangling.success, fact).toBe(false);
if (dangling.success)
throw new Error(`Expected dangling ${fact} reference`);
expect(
@@ -711,7 +641,6 @@ it("validates evidence context ownership and references", () => {
...graph.nodes.slice(1),
],
});
expect(impossibleEvidence.success).toBe(false);
if (impossibleEvidence.success)
throw new Error("Expected incompatible evidence context and location");
expect(
@@ -739,10 +668,47 @@ it("shares provenance contexts while preserving fact-specific locations and unkn
},
evidenceContexts,
);
expect(second.evidence.context_id).toBe(first.evidence.context_id);
expect(second.evidence.location).not.toEqual(first.evidence.location);
const { graph_id: _graphId, ...semantic } = graph;
const combined = createJavaScriptSemanticGraph({
...semantic,
unknowns: [...graph.unknowns, second],
evidence_contexts: evidenceContexts.contexts,
coverage: {
...graph.coverage,
families: graph.coverage.families.map((family) =>
family.unknown_ids.includes(first.unknown_id)
? {
...family,
unknown_ids: [...family.unknown_ids, second.unknown_id],
}
: family,
),
},
});
const stored = javaScriptSemanticGraphSchema.parse(
JSON.parse(JSON.stringify(combined)),
);
expect(stored.evidence_contexts).toEqual(graph.evidence_contexts);
expect(second.unknown_id).not.toBe(first.unknown_id);
expect(evidenceContexts.contexts).toEqual(graph.evidence_contexts);
expect(stored.unknowns).toEqual(
expect.arrayContaining([
expect.objectContaining({
unknown_id: first.unknown_id,
evidence: first.evidence,
}),
expect.objectContaining({
unknown_id: second.unknown_id,
evidence: {
context_id: first.evidence.context_id,
location: {
available: false,
reason: "unresolved",
detail: "Another source location remains unresolved.",
},
},
}),
]),
);
});
const complete = <Value>(steps: Iterator<void, Value>): Value => {
@@ -772,12 +738,13 @@ it("preserves a transferred graph independent of the caller retained copy", () =
input.coverage.families.length = 0;
const graph = complete(steps);
expect(graph).toEqual(expected);
const nodeIds = graph.nodes.map(({ node_id }) => node_id);
expect(nodeIds).toEqual(nodeIds.toSorted());
expect(
javaScriptSemanticGraphSchema.parse(JSON.parse(JSON.stringify(graph))),
).toEqual(expected);
expect(isValidatedImmutableJavaScriptSemanticGraph(graph)).toBe(true);
expect(isValidatedImmutableJavaScriptSemanticGraph(expected)).toBe(false);
expect(Object.isFrozen(nested)).toBe(false);
});
const invalidGraphCases: {
@@ -880,22 +847,17 @@ it.each(invalidGraphCases)(
},
);
it("interns each distinct evidence context once under its content digest", () => {
it("interns valid normalized evidence after rejecting malformed provenance", () => {
const registry = new JavaScriptSemanticEvidenceContextRegistry();
const elsewhere: ApplicationGraphEvidence = {
...semanticGraphTestEvidence(),
location: {
available: true,
value: {
kind: "source-range",
source: "other.js",
start: { line: 7, column: 2 },
end: { line: 7, column: 9 },
},
},
};
const first = registry.intern(semanticGraphTestEvidence());
const repeated = registry.intern(elsewhere);
const observed = semanticGraphTestEvidence();
expect(() =>
registry.intern({
...observed,
extractor: { ...observed.extractor, name: "" },
}),
).toThrow(z.ZodError);
const first = registry.intern(observed);
const reordered = registry.intern({
...semanticGraphTestEvidence("inferred"),
limitations: [
@@ -904,10 +866,8 @@ it("interns each distinct evidence context once under its content digest", () =>
],
});
const inferred = registry.intern(semanticGraphTestEvidence("inferred"));
const { location: _location, ...context } = semanticGraphTestEvidence();
const { location: _location, ...context } = observed;
expect(repeated.context_id).toBe(first.context_id);
expect(repeated.location).toEqual(elsewhere.location);
expect(reordered.context_id).toBe(inferred.context_id);
expect(inferred.context_id).not.toBe(first.context_id);
expect(first.context_id).toBe(
@@ -916,19 +876,7 @@ it("interns each distinct evidence context once under its content digest", () =>
expect(registry.contexts.map(({ context_id }) => context_id)).toEqual(
[first.context_id, inferred.context_id].toSorted(),
);
expect(registry.resolve(repeated)).toEqual(elsewhere);
});
it("rejects invalid provenance in direct registry.intern calls before sealing", () => {
const registry = new JavaScriptSemanticEvidenceContextRegistry();
const baseEvidence = semanticGraphTestEvidence();
expect(() =>
registry.intern({
...baseEvidence,
extractor: { ...baseEvidence.extractor, name: "" },
}),
).toThrow(z.ZodError);
expect(registry.ownedContexts).toEqual([]);
expect(registry.resolve(first)).toEqual(observed);
});
it("seals owned builder records while still rejecting tampered spread copies", () => {
@@ -115,23 +115,6 @@ const registryForGraph = (
return registry;
};
it("returns every relevant unknown inline", () => {
const graph = semanticFixtureGraph(true);
const callable = graph.nodes.find(({ kind }) => kind === "function");
if (callable === undefined) throw new Error("Expected callable node");
const result = queryJavaScriptSemanticGraph(
graph,
javaScriptSemanticQueryInputSchema.parse({
seed: { kind: "semantic-node", node_id: callable.node_id },
direction: "forward-influence",
}),
);
expect(result).toMatchObject({
summary: { relevant_unknowns: 1 },
});
expect(result.unknowns).toHaveLength(1);
});
it("does not admit a semantic-node seed absent from the graph", () => {
const result = queryJavaScriptSemanticGraph(
semanticFixtureGraph(),
@@ -149,102 +132,67 @@ it("does not admit a semantic-node seed absent from the graph", () => {
});
});
it("returns the complete deterministic forward influence result inline", () => {
const graph = semanticFixtureGraph();
const input = {
seed: { kind: "literal" as const, value: "TOKEN" },
direction: "forward-influence" as const,
expected: { role: "sink" as const, classes: ["request" as const] },
};
const first = queryJavaScriptSemanticGraph(
graph,
javaScriptSemanticQueryInputSchema.parse(input),
);
expect(first).toMatchObject({
status: "found",
summary: { traversed_nodes: 4, traversed_relations: 3 },
relations: expect.any(Array),
});
expect(first.expected_match_node_ids).toHaveLength(1);
expect(first.relations).toHaveLength(3);
});
it("returns only the referenced evidence contexts with resolvable trace facts", () => {
const graph = semanticFixtureGraph();
const result = queryJavaScriptSemanticGraph(
graph,
javaScriptSemanticQueryInputSchema.parse({
seed: { kind: "literal", value: "TOKEN" },
direction: "forward-influence",
}),
);
const expectedContextIds = [
...new Set([
...result.nodes.map(({ evidence }) => evidence.context_id),
...result.relations.map(({ evidence }) => evidence.context_id),
...result.unknowns.map(({ evidence }) => evidence.context_id),
]),
].sort();
expect(result.evidence_contexts.map(({ context_id }) => context_id)).toEqual(
expectedContextIds,
);
for (const node of result.nodes)
expect(resolveJavaScriptSemanticEvidence(result, node.evidence)).toEqual(
resolveJavaScriptSemanticEvidence(graph, node.evidence),
);
});
it("traverses a path of 70 relations", () => {
it("returns reachable influence facts and only their evidence contexts", () => {
const original = semanticFixtureGraph();
const input = constructionInput(original);
const evidenceContexts = registryForGraph(original);
const request = original.nodes.find(({ kind }) => kind === "request");
if (request === undefined) throw new TypeError("Missing request node");
const chain = Array.from({ length: 70 }, (_, index) =>
node("binding", `long-chain-${index}`, evidenceContexts),
);
const chainRelations = chain.map((target, index) =>
createJavaScriptSemanticGraphRelation(
{
source_node_id: chain[index - 1]?.node_id ?? request.node_id,
target_node_id: target.node_id,
relation: "reads",
resolution: "resolved",
properties: {},
evidence: semanticGraphTestEvidence("inferred"),
const moduleNode = original.nodes.find(({ kind }) => kind === "module");
if (moduleNode === undefined)
throw new Error("Expected the unreachable module");
const { node_id: _moduleId, evidence, ...moduleInput } = moduleNode;
const moduleEvidence = resolveJavaScriptSemanticEvidence(original, evidence);
const unrelated = createJavaScriptSemanticGraphNode(
{
...moduleInput,
evidence: {
...moduleEvidence,
extractor: { ...moduleEvidence.extractor, name: "unreachable-module" },
},
evidenceContexts,
),
},
evidenceContexts,
);
const graph = createJavaScriptSemanticGraph({
...input,
...constructionInput(original),
nodes: original.nodes.map((entry) =>
entry.node_id === moduleNode.node_id ? unrelated : entry,
),
evidence_contexts: evidenceContexts.contexts,
nodes: [...input.nodes, ...chain],
relations: [...input.relations, ...chainRelations],
coverage: {
...original.coverage,
families: original.coverage.families.map((family) =>
family.family === "data-flow"
? {
...family,
retained_relations:
family.retained_relations + chainRelations.length,
}
: family,
),
},
});
const result = queryJavaScriptSemanticGraph(
graph,
javaScriptSemanticQueryInputSchema.parse({
seed: { kind: "literal", value: "TOKEN" },
direction: "forward-influence",
expected: { role: "sink", classes: ["request"] },
}),
);
expect(result.summary.traversed_nodes).toBe(74);
expect(result.nodes).toHaveLength(74);
expect(result).toMatchObject({
status: "found",
summary: { traversed_nodes: 4, traversed_relations: 3 },
});
expect(result.nodes.map(({ kind }) => kind).sort()).toEqual([
"binding",
"function",
"literal",
"request",
]);
expect(result.relations.map(({ relation }) => relation).sort()).toEqual([
"captures",
"constructs-request",
"defines",
]);
expect(result.expected_match_node_ids).toEqual([
original.nodes.find(({ kind }) => kind === "request")?.node_id,
]);
expect(result.evidence_contexts).toEqual(
graph.evidence_contexts.filter(
({ context_id }) => context_id !== unrelated.evidence.context_id,
),
);
for (const fact of [...result.nodes, ...result.relations])
expect(resolveJavaScriptSemanticEvidence(result, fact.evidence)).toEqual(
resolveJavaScriptSemanticEvidence(graph, fact.evidence),
);
});
it("accepts deeply nested semantic properties", () => {
@@ -263,8 +211,9 @@ it("accepts deeply nested semantic properties", () => {
});
it("keeps relevant dynamic frontiers unknown", () => {
const graph = semanticFixtureGraph(true);
const result = queryJavaScriptSemanticGraph(
semanticFixtureGraph(true),
graph,
javaScriptSemanticQueryInputSchema.parse({
seed: { kind: "literal", value: "TOKEN" },
direction: "forward-influence",
@@ -272,12 +221,11 @@ it("keeps relevant dynamic frontiers unknown", () => {
);
expect(result.status).toBe("partial");
expect(result.coverage.status).toBe("partial");
expect(result.unknowns).toMatchObject([
{ reason: "dynamic-call", relation_kinds: ["calls"] },
]);
expect(result.summary.relevant_unknowns).toBe(1);
expect(result.unknowns).toEqual(graph.unknowns);
});
it("reports partial status when retained graph facts were truncated", () => {
it("reports a partial trace when the graph has unknown omission counts", () => {
const graph = semanticFixtureGraph();
const partial = createJavaScriptSemanticGraph({
...constructionInput(graph),
@@ -291,6 +239,12 @@ it("reports partial status when retained graph facts were truncated", () => {
},
limitations: ["The node ceiling left omission extents unknown."],
});
expect(partial.coverage).toMatchObject({
status: "partial",
truncated: true,
omitted_nodes: null,
omitted_relations: null,
});
const result = queryJavaScriptSemanticGraph(
partial,
javaScriptSemanticQueryInputSchema.parse({
@@ -594,7 +548,14 @@ it("keeps candidate uncertainty at the end of a long reachable path", () => {
expect(result).toMatchObject({
status: "ambiguous",
coverage: { status: "partial" },
summary: {
traversed_nodes: include ? 72 : 71,
traversed_relations: include ? 71 : 70,
},
});
expect(result.nodes).toHaveLength(include ? 72 : 71);
const reachable = include ? chain : chain.slice(0, -1);
expect(result.nodes.map(({ node_id }) => node_id).toSorted()).toEqual(
reachable.map(({ node_id }) => node_id).toSorted(),
);
}
});